1

I am writing a program that recognizes if a number is a perfect square. Obviously the factors of the perfect square have to be integers. So I was wondering what would be the best way to recognize whether the sqrt of the user input (via Scanner) is an integer or a double.

thanks in advance.

radoh
  • 4,554
  • 5
  • 30
  • 45
Ronald
  • 77
  • 10
  • 2
    You could use `Math.round` and compare the values; you could convert the input to a `int` and compare the values; you could get a `String` value and check for a `.` – MadProgrammer Oct 21 '15 at 23:22
  • 2
    Possible duplicate of [How to test if a double is an integer](http://stackoverflow.com/questions/9898512/how-to-test-if-a-double-is-an-integer) – Siddhartha Oct 21 '15 at 23:30
  • @Siddhartha i checked that thread before i posted. we did not go over the .floor concept in class so therefore i did not know how to implement it. – Ronald Oct 21 '15 at 23:40

2 Answers2

0

I'm assuming your code contains the following statements:

      Scanner userIn = new Scanner(System.in);
    //userIn.next() somewhere in your code, which is what you want to test

You could use the following method (pass userIn.next() as an argument):

        public boolean isDouble(String userInput){
               if(userInput.contains(".")){
                     return true;
               }
               else{
                    return false;
               }
        }

This code basically checks if the userInput String contains a decimal point, if so the input is a double else it would be a false, you could also add preliminary conditions to make sure that the userInput is a number and not anything else.


EDIT: As Klitos Kyriacou has rightfully pointed out in the comments, my answer did not initially answer the question asked, however the OP was satisfied... for the sake of completeness, I will answer the question specifically:

The sqrt method from the static class Math returns a double, so using the test above will not work as Math.sqrt(25) will return 5.0.

To go about this one can simply compare the rounded value of the sqrt's return value to the actual return value of the sqrt method.

You could use the following method (As in the case above userIn.next(), will be the argument to the method):

 public boolean isPerfectSquare(String userInput){
        if(Math.sqrt(Double.parseDouble(userInput)) == Math.round(Math.sqrt(Double.parseDouble(userInput)))){
            return true;
        }
        return false;
    }
RamanSB
  • 1,162
  • 9
  • 26
0

Compute the square root and compare it with itself cast to an integer, or the result of Math.floor() if the numbers can be large.

user207421
  • 305,947
  • 44
  • 307
  • 483