Skip to content
Advertisement

Why do I need to assign -1 to an int for a random number guesser in Java

this is my first question here so I apologize if this has been answered before. I am working through beginner loops in university and am following along my textbook to program a number guesser. The code works, but what I don’t understand is why on line 17 I needed to create an int and give it a value of -1. Screenshot of code here. Any explanation would be great, thanks!

Advertisement

Answer

This is simply to guarantee that the loop doesn’t exit on the first time through. The while condition is evaluated before the code inside it is. If it had been initialized to 0 and the number had been 0, none of the code inside the while would have been executed. Think about with this part of your code

int number = (int)(0 * 101) //Math.random() returned 0
int guess = 0;
while(guess != number) // while(0 != 0) this is always true so the while loop won't be executed

It isn’t likely that you will ever have this actually affect your output, it is a possibility, and so rather than check if number is 0, guess is set to a number that it is guaranteed to execute the while loop at least once.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement