/你好,我正在尝试学习如何在 java 中使用“break”命令以及使用“y 或 n”选项继续循环。我正在写这个猜数游戏,我在选择“y”时遇到了一些麻烦。我会试着解释一下,写一个猜数字的游戏很容易,所以我开始添加一些条件,比如是否再次玩的可能性,后来我想如果我添加退出的可能性会更有趣时间玩家希望,但这不能正常工作。请帮忙,这是我的代码
package guessinggame;
import java.util.Random;
import java.util.Scanner;
/**
*
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
}
}