我用Java编写了一个小程序:
String grade = JOptionPane.showInputDialog("What is your grade?");
switch (grade)
{
case "A":
JOptionPane.showMessageDialog(null, "You got an A - Well done!");
break;
case "B":
JOptionPane.showMessageDialog(null, "You got a B - Very good!");
break;
case "C":
JOptionPane.showMessageDialog(null, "You got a C - Good!");
break;
case "D":
JOptionPane.showMessageDialog(null, "You got a D - Study better next time!");
break;
default:
JOptionPane.showMessageDialog(null, "Invalid grade!");
}
}
}
现在,问题是 - 如果用户输入的评分无效,则“评分无效!”消息出现,按“确定”后它就会关闭。
如何在无效成绩消息后让程序返回到输入阶段?
答案 0 :(得分:2)
使用带有标记的do-while
循环:
boolean wrongInput = false;
do {
wrongInput = false;
String grade = JOptionPane.showInputDialog("What is your grade?");
switch (grade)
{
case "A":
JOptionPane.showMessageDialog(null, "You got an A - Well done!");
break;
case "B":
JOptionPane.showMessageDialog(null, "You got a B - Very good!");
break;
case "C":
JOptionPane.showMessageDialog(null, "You got a C - Good!");
break;
case "D":
JOptionPane.showMessageDialog(null, "You got a D - Study better next time!");
break;
default:
JOptionPane.showMessageDialog(null, "Invalid grade!");
wrongInput = true;
}
} while(wrongInput);
答案 1 :(得分:0)
您可以使用while
循环和标签来执行此操作:
loop: while (true) {
String grade = JOptionPane.showInputDialog("What is your grade?");
switch (grade)
{
case "A":
JOptionPane.showMessageDialog(null, "You got an A - Well done!");
break loop;
case "B":
JOptionPane.showMessageDialog(null, "You got a B - Very good!");
break loop;
case "C":
JOptionPane.showMessageDialog(null, "You got a C - Good!");
break loop;
case "D":
JOptionPane.showMessageDialog(null, "You got a D - Study better next time!");
break loop;
default:
JOptionPane.showMessageDialog(null, "Invalid grade!");
}
}