import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main (String [] args) {
Random rand = new Random ();
int numberToGuess = rand.nextInt (100);
int numberOfTries = 0;
Scanner input = new Scanner (System.in);
int guess;
boolean win = false;
while (win == false); {
System.out.println("Guess a number between 1 and 100:");
guess = input.nextInt ();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
}
else if (guess > numberToGuess) {
System.out.println ("You guessed too low mate!");
}
else if (guess > numberToGuess) {
System.out.println ("You guessed too high mate!") ;
System.out.println("You win!!");
System.out.println("The random number WAS!" + numberToGuess);
System.out.println("It took you a wopping" + numberOfTries + "TRIES!");
}
}
}
}
这是我的代码,当我尝试运行它时,它基本上卡在这里:
欢迎来到Java博士。 工作目录是U:\ Downloads 运行GuessingGame
如何解决这个问题,我可以正确运行程序,而不会出现上述错误?
答案 0 :(得分:2)
我看到两个错误。
while (win == false); {
应该是
while (win == false) {
(或while(!win) {
)因为分号会创建一个空循环体。和
else if (guess > numberToGuess) {
System.out.println ("You guessed too low mate!");
}
应该是
else if (guess < numberToGuess) {
System.out.println ("You guessed too low mate!");
}
或者你有更高的两个测试(这种方式很有意义)。
答案 1 :(得分:1)
详细说明艾略特的答案:
while (win == false); {
// etc. etc. etc.
}
相当于
while (win == false)
; // empty statement, does nothing
{
// The body, which really isn't part of the while loop any more
}
与
具有相同的效果while (win == false) {
}
{
// The part that isn't really part of the loop
}
由于win
从false
开始,所以在win
以某种方式变为true
之前,这将继续循环并且什么都不做,这当然永远不会发生。这就是程序陷入困境的原因 - 它处于无限循环中。
答案 2 :(得分:1)
将while
块修改为do-while
块,如下所示
do{
System.out.println("Guess a number between 1 and 100:");
guess = input.nextInt ();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
}
else if (guess < numberToGuess) {
System.out.println ("You guessed too low mate!");
}
else if (guess > numberToGuess) {
System.out.println ("You guessed too high mate!") ;
System.out.println("You win!!");
System.out.println("The random number WAS!" + numberToGuess);
System.out.println("It took you a wopping" + numberOfTries + "TRIES!");
}
}while(win==false);