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

Time:10-28

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!

CodePudding user response:

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.

CodePudding user response:

You can initialize the variable guess to any integer. u just need a integer to compare it with the variable number . feel free to replace it with any integer as it re initialized in while loop if it is not equal to variable number .

CodePudding user response:

You will need a loop to ask the question several times till the answer is correct. In a loop you can test the value of a variable in the beginning of the loop or in the end. If you test in the beginning of the loop, then the variable must have a value, otherwise the program would not compile. So, to start the loop you must give any value that for sure is not the correct answer, for example any negative number or any number greater than 100.

  • Related