gpt4 book ai didi

java - 我的循环出现问题,想要以正确的选择终止(JAVA)

转载 作者:行者123 更新时间:2023-12-01 17:20:38 25 4
gpt4 key购买 nike

import javax.swing.JOptionPane;

public class Quiz {

public static void main(String[] args) {

String question = ("How many states are there in the United States of America?\n");
question += "A. There are 48 states.\n";
question += "B. There are 50 states.\n";
question += "C. There are 52 states.\n";
question += "D. There are 13 states.\n";
question += "E. There are 26 states.\n";

while (true) {
String answer = JOptionPane.showInputDialog(question);
answer = answer.toUpperCase();
if (answer.equals("B")) {
JOptionPane.showMessageDialog(null,"Correct!");}
switch (answer)
{
//case "B":
//JOptionPane.showMessageDialog(null,"Correct!");
//break;
case "A":
JOptionPane.showMessageDialog(null,"You chose A, that is incorrect. Please try again");
break;
case "C":
JOptionPane.showMessageDialog(null,"You chose C, that is incorrect. Please try again");
break;
case "D":
JOptionPane.showMessageDialog(null,"You chose D, that is incorrect.Please try again");
break;
case "E":
JOptionPane.showMessageDialog(null,"You chose E, that is incorrect.Please try again");
break;
default:
JOptionPane.showMessageDialog(null,"You made an invalid selection, please enter A,B,C,D, or E.");
break;
}


}
}
}

我试图让程序在选择正确答案后停止询问问题。如果选择了错误的选择,我希望出现问题,直到用户选择正确的答案,然后让程序终止。现在,我在选择正确答案后出现“默认”语句,并且它不会终止。

最佳答案

如果您知道当答案为 B 时您的程序将终止,则应该删除 while(true),并且也许可以执行类似的操作。

import javax.swing.JOptionPane;

public class Quiz {

public static void main(String[] args) {

String question = ("How many states are there in the United States of America?\n");
question += "A. There are 48 states.\n";
question += "B. There are 50 states.\n";
question += "C. There are 52 states.\n";
question += "D. There are 13 states.\n";
question += "E. There are 26 states.\n";
String answer = "";
// This will work with 'B' and 'b' because your setting your answer to uppercase
while (!answer.equals("B")) {
answer = JOptionPane.showInputDialog(question);
answer = answer.toUpperCase();
switch (answer) {
case "B":
JOptionPane.showMessageDialog(null,"Correct!");
break;
case "A":
JOptionPane.showMessageDialog(null,"You chose A, that is incorrect. Please try again");
break;
case "C":
JOptionPane.showMessageDialog(null,"You chose C, that is incorrect. Please try again");
break;
case "D":
JOptionPane.showMessageDialog(null,"You chose D, that is incorrect.Please try again");
break;
case "E":
JOptionPane.showMessageDialog(null,"You chose E, that is incorrect.Please try again");
break;
default:
JOptionPane.showMessageDialog(null,"You made an invalid selection, please enter A,B,C,D, or E.");
break;
}


}
}
}

由于注释了 B case 行,您可能会得到默认语句。

关于java - 我的循环出现问题,想要以正确的选择终止(JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61298902/

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