我刚刚开始学习使用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);
请帮忙。
答案 0 :(得分:1)
您的问题是您正在计算循环的有效 。 换句话说:你计算一次;在你进入循环之前;然后,在你的循环中,你再也不会触及它的价值了。
因此,你的循环所做的“唯一”事情就是一遍又一遍地提升那个对话。
因此:你必须在循环中移动所有的那些计算!
所以,不仅仅是
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);
}
现在你可以通过简单地调用该方法并在循环体中检查其结果来更容易地循环!