输入特定字符时的 Java 重放
Posted
技术标签:
【中文标题】输入特定字符时的 Java 重放【英文标题】:Java replay when certain character typed 【发布时间】:2022-01-24 04:40:24 【问题描述】:当猜对后输入数字 0 时,它应该重玩游戏。它只是返回消息“0 再次播放,1 退出”
public static void main(String[] args)
boolean game = true; //true means the game will continue playing, false stops the game
Scanner input = new Scanner(System.in);
System.out.println("Guess: ");
while (game)
HiLo mainGame = new HiLo();
mainGame.generateRandomNumber();
boolean guessCorrect = false;
while (!guessCorrect)
int inputted = input.nextInt();
if (inputted == 101)
guessCorrect = true;
System.out.println("quitted");
System.out.println(mainGame.checkGuess(inputted));
mainGame.getGuessCounter();
if (mainGame.checkGuess(inputted) == "Correct! You got it right!")
guessCorrect = true;
System.out.println("Correct after " + mainGame.getGuessCounter() + " guesses");
while (guessCorrect = true)
System.out.println("Would you like to play again? (0 : YES) (1 : NO)");
System.out.println("Your answer: ");
int answer = input.nextInt();
//issues with inputting 0 and restarting game
if (answer == 0)
game = true;
else if (answer == 1)
guessCorrect = true;
System.out.println("Game Over");
else
System.out.println("Error, can't understand the meaning");
guessCorrect = false;
【问题讨论】:
while (guessCorrect = true)
那应该只是while (guessCorrect)
if (mainGame.checkGuess(inputted) == "Correct! You got it right!")
我找不到方法 checkGuess
的代码,但我认为它返回一个字符串。请参考How do I compare strings in Java
嗨,OP。让我们知道答案是否有帮助。如果它回答了您的问题,请接受它。这样其他人就知道你已经(充分地)得到了帮助。另见What should I do when someone answers my question?
【参考方案1】:
将while (guessCorrect = true)
更改为while (guessCorrect)
。将guessCorrect
设置为false
以退出while (guessCorrect)
循环并继续重新启动或退出游戏。如果answer
不等于0
,请确保将game
设置为false
以退出游戏。
while (guessCorrect)
System.out.println("Would you like to play again? (0 : YES) (1 : NO)");
System.out.println("Your answer: ");
int answer = input.nextInt();
//issues with inputting 0 and restarting game
if (answer == 0)
game = true;
else if (answer == 1)
System.out.println("Game Over");
game = false;
else
System.out.println("Error, can't understand the meaning");
game = false;
guessCorrect = false;
【讨论】:
以上是关于输入特定字符时的 Java 重放的主要内容,如果未能解决你的问题,请参考以下文章