简体   繁体   English

为什么我需要为 Java 中的随机数猜测器的 int 分配 -1

[英]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.该代码有效,但我不明白为什么在第 17 行我需要创建一个 int 并为其赋予 -1 的值。 Screenshot of code here .代码截图在这里 Any explanation would be great, thanks!任何解释都会很棒,谢谢!

You can initialize the variable guess to any integer.您可以将变量 guess 初始化为任何整数。 u just need a integer to compare it with the variable number .你只需要一个整数来将它与变量 number 进行比较。 feel free to replace it with any integer as it re initialized in while loop if it is not equal to variable number .如果它不等于变量 number ,请随意用任何整数替换它,因为它在 while 循环中重新初始化。

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. while条件在它内部的代码之前被评估。 If it had been initialized to 0 and the number had been 0, none of the code inside the while would have been executed.如果它已被初始化为 0 并且数字为 0,则while内的任何代码都不会被执行。 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.您不太可能让这实际影响您的输出,这是一种可能性,因此与其检查number是否为 0,不如将guess设置为一个可以保证至少执行一次 while 循环的数字。

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.因此,要开始循环,您必须给出任何肯定不是正确答案的值,例如任何负数或任何大于 100 的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM