Code to flag a square number is not working, why is this?

Viewed 40

I am trying to learn Java and have to create a small script that tells you if a number you have selected is a square number or not:

public class NumberShapes{
    public static void main(String[] args) {

        class Number {
            int number;

            public boolean isSquare(){
                int y = 1;
                int squareNumber = 1;

                while (squareNumber <= number) {
                    y += 1;
                    squareNumber = (y * y);
                }

                if (squareNumber == number) {
                    return true;
                }
                else {
                    return false;
                }
            }

        }
        Number myNumber = new Number();

        myNumber.number = 9;

        System.out.println("Is " + myNumber.number + " a square number?: " + myNumber.isSquare());

}
}

Let's say you choose a number, in this case myNumber = 9. The logic is then supposed to take every integer < 9 and square it. If any number is squared to equal myNumber, then myNumber is a square number (and returns true) otherwise it isn't and returns false.

However when I try with 9, I get the output to be false, when it should be true.

My thinking is that somehow it squares numbers up to 9, but then instead of comparing 9 with 9, it is comparing 3 with 9, and as 3 != 9, it outputs as false. Is this correct?

How would I fix it?

(Just FYI, I have seen an alternative where you can square root the number and check if it is an integer, but I would like to figure out why this way isn't working).

1 Answers

The problem is in your loop's condition:

while (squareNumber <= number) {
    y += 1;
    squareNumber = (y * y);
}

When y reaches 3, and squareNumber becomes 9 (3 * 3), you are not exiting the loop, since 9 <= 9 is true. Therefore, in the next iteration of the loop, you assign 4 * 4 to squareNumber before ending the loop, and you return false.

Change the condition to while (squareNumber < number).

Related