gpt4 book ai didi

java - 用户输入正确答案后,如何停止重复此循环?

转载 作者:行者123 更新时间:2023-11-30 07:08:42 24 4
gpt4 key购买 nike

我才刚刚开始学习用java编写代码,我已经尝试解决这个问题一段时间了,我已经尝试了各种方法,并且我尝试过寻找类似的方法问题,但我找不到答案。

我试图在用户输入不等于 1、2 或 3 时重复循环。然后在输入正确答案后停止重复。

    // create a menu and display it to the user
// then ask the user to choose an option
String menu = "1) See Rules\n"
+ "2) Play the Game\n"
+ "3) Exit\n"
+ "Please enter your choice: (1 or 2 or 3) ";

String userChoice = JOptionPane.showInputDialog(menu);

JOptionPane.showMessageDialog(null, "You chose option " + userChoice);

// display the rules
String rules = "Rules:\n"

+ "The game will display total 3 multiple choice questions," +
" with 4 possible answers per question.\n"
+ "Once you answer the question, the correct answer will be displayed" +
" and the game will advance to the next question.\n"
+ "If you answer the question correctly, you will gain a point.\n"
+ "Each point is added to a total score that will be displayed at the" +
"end of the game.\n";

// declare an integer that reads the user input
int numericChoice = Integer.parseInt(userChoice);

boolean valid = (numericChoice == 1 || numericChoice == 2 || numericChoice == 3);

while (true)
{
if (!valid) {
JOptionPane.showMessageDialog(null, "Invalid selection, please try again");
JOptionPane.showInputDialog(menu);
} if (valid){
break;
}

if (numericChoice == 1){
// display the rules then start the game
JOptionPane.showMessageDialog(null, rules);
}
else if (numericChoice == 2){
// start the game
JOptionPane.showMessageDialog(null, "Let's play the game.\n");
}
else if (numericChoice == 3)
// exit the game
System.exit(0);

请帮忙。

最佳答案

您的问题是您正在循环之外计算有效。换句话说:你计算一次;在进入循环之前;然后,在循环中,您再也不会触及它的值。

因此,循环所做的“唯一”事情就是一遍又一遍地引发该对话框。

因此:您必须在循环内移动所有这些计算!

所以,不仅

boolean valid = (numericChoice == 1 || numericChoice == 2 || numericChoice == 3);

需要进入循环,还需要进入获取用户输入的代码,并确定numericChoice!

您可以做的是编写一个辅助方法,例如:

private int showMenuAndGetUserChoice() {
// create a menu and display it to the user
// then ask the user to choose an option
String menu = "1) See Rules\n" ...
String userChoice = JOptionPane.showInputDialog(menu);
JOptionPane.showMessageDialog(null, "You chose option " + userChoice); ...

return Integer.parseInt(userChoice);
}

现在,您可以更轻松地循环,只需调用该方法并在循环体内检查其结果即可!

关于java - 用户输入正确答案后,如何停止重复此循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39584320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com