我很新,找不到我想要的确切答案。我试图使用JOptionPane创建一个非常简单的循环,其中我插入1-10之间的值并保持循环它。如果值超过10或低于1,您应该要求用户再试一次。到目前为止,我有这个。如果值达到0,则程序应该结束。
String ans_s = JOptionPane.showInputDialog( "Please enter a rating between 1-10 (0 to stop)");
int number = Integer.parseInt(ans_s);
if (number > 10 || number < 0) {
JOptionPane.showMessageDialog( null, "Please Try Again");
ans_s = JOptionPane.showInputDialog( "Please enter a number between 1-10 (0 to stop)");
number = Integer.parseInt(ans_s);
}
else if (number < 10 || number > 0) {
ans_s = JOptionPane.showInputDialog( "Please enter a rating between 1-10 (0 to stop)");
}
else if (number == 0) {
JOptionPane.showMessageDialog(null, "Finished");
}
似乎没有什么循环所以我只需要一些指导。谢谢
答案 0 :(得分:0)
你需要一个循环结构,
boolean control_statement = true;
while (control_statement) {
codeInThisMethodWillLoop(); //Until control_statement = false
}
或
final int maxLoops = 10; //can be any number
for (int loopCounter = 0; loopCounter < maxLoops; loopCounter++) {
codeInThisMethodWillLoop(); //Until loopCounter = maxLoops
}
在你的情况下
int number = -1;
while (number != 0) {
String ans_s = JOptionPane.showInputDialog( "Please enter a rating between 1-10 (0 to stop)");
number = Integer.parseInt(ans_s);
if (number > 10 || number < 0) {
JOptionPane.showMessageDialog( null, "Please Try Again");
ans_s = JOptionPane.showInputDialog( "Please enter a number between 1-10 (0 to stop)");
number = Integer.parseInt(ans_s);
}
else if (number < 10 || number > 0) {
ans_s = JOptionPane.showInputDialog( "Please enter a rating between 1-10 (0 to stop)");
}
else if (number == 0) {
JOptionPane.showMessageDialog(null, "Finished");
}
}