我面临着使游戏结束的问题!
我创建了int numberOfTries = 0并试图使游戏结束 的numberOfTries> 4。 我不知道问题出在哪里?
do {
int theNumber = (int) (Math.random() * 100 +1 );
int guess = 0;
int numberOfTries = 0;
while (guess != theNumber){
System.out.println("Guess a number between 1 and 100");
guess = scan.nextInt();
if (guess< theNumber) {
System.out.println(guess + " is too low.");
numberOfTries += 1 ;
}
else if ( guess > theNumber) {
System.out.println(guess + " is too high.");
numberOfTries += 1;
}
else if(guess == theNumber) {
System.out.println(guess + " is correct!");
if (numberOfTries == 1 ){
System.out.println("You are a genius!");
}
else if (numberOfTries == 0){
System.out.println("You are a pure genius!");
}
else if (numberOfTries <=4 ){
System.out.println("It only took you " + numberOfTries +
" Good Job!");
}
}
else if (numberOfTries > 4){
System.out.println("Game over!");
}
}
System.out.println("Would you like to play again?(y/n)");
playAgain = scan.next();
}while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing this game! Good Bye!");
scan.close();
}
}
有人可以向我解释一下吗? 谢谢
答案 0 :(得分:1)
您的else构造看起来像这样:
if (guess< theNumber) {
}
else if ( guess > theNumber) {
}
else if(guess == theNumber) {
}
else if (numberOfTries > 4){
}
因此,首先您要询问猜测值是否小于数字,然后是数字,如果不是,则等于数字。
现在,您的if-else构造已经用尽了所有可能的状态,因为一个数字必须更大,更小或等于另一个数字,所以将永远不会输入最后一个if。
只要将最后一个else更改为普通if,
if (numberOfTries > 4){
}
答案 1 :(得分:0)
当尝试次数超过4次时,应该打破循环。不仅仅是打印出消息。
答案 2 :(得分:0)
您的陈述是否总是在三个条件之一中输入,因此,请不要在最后一个条件中输入。 一种解决方案是更改此地址:
else if (numberOfTries > 4){
System.out.println("Game over!");
}
为此:
if (numberOfTries > 4){
System.out.println("Game over!");
break;
}