4 回答

TA貢獻1877條經驗 獲得超1個贊
使用do-while至少執行一次的循環,如果days不滿足條件則每次都循環回來。
public static void main(String[] args)
{
do {
//Your other code
String animal = JOptionPane.showInputDialog("Enter In Animal Name"); // Asking for user to enter a animal
String fruit = JOptionPane.showInputDialog("Enter In A Fruit Name"); // Asking user to enter a fruit
int days = askForInput();
if (days <= 0 || days >= 10) { // Ensures that negative numbers cannot be entered.
JOptionPane.showMessageDialog(null, "Error, Please enter a number between 1 and 10");
}
} while (days <= 0 || days >= 10);
}
//Pass whatever parameters you might need
public static int askForInput() {
int days = Integer.parseInt(JOptionPane.showInputDialog("Enter In How Many Days Between 1 And 10"));
//Any other code you want
return days;
}
我還將它提取到一個方法中,這可能是不必要的,但如果需要,它可以讓您添加更多功能。
如果您不想每次都被問到這個問題,您也可以移動animal或fruit離開。do

TA貢獻1779條經驗 獲得超6個贊
允許代碼重新啟動代碼塊(即返回到開頭并重試)的一種方法是使用帶有“永遠”循環的continueand語句。break
for (;;) { // loop forever
// some code here
if (failure condition 1) {
// handle failure here
continue; // go back and try again
}
if (failure condition 2) {
// handle failure here
continue; // go back and try again
}
// more code and failure condition checks here
break; // unconditional exit loop, since all is ok
}
如果“此處的某些代碼”本身位于循環內,但需要返回到開頭并重試,則可以為此使用標簽:
TRYAGAIN: for (;;) { // loop forever
// some code here
for (some looping here) {
// some code here
try {
if (failure condition) {
// handle failure here
continue TRYAGAIN; // go back and try again
}
} finally {
// code here will execute, even if 'continue' is used
}
}
// more code and failure condition checks here
break; // unconditional exit loop, since all is ok
}

TA貢獻1829條經驗 獲得超7個贊
String animal;
String fruit;
int days = 0;
animal = JOptionPane.showInputDialog("Enter In Animal Name");
fruit = JOptionPane.showInputDialog("Enter In A Fruit Name");
while(days <= 0 || days > 10) {
days = Integer.parseInt(JOptionPane.showInputDialog("Enter In How Many Days Between 1 And 10"));
if (days <= 0 || days > 10) {
JOptionPane.showMessageDialog(null, "Error, Please enter a number between 1 and 10");
}
}

TA貢獻1982條經驗 獲得超2個贊
使用 while 循環
// Your user prompt for animal and fruit goes here
boolean exit = false;
while(!exit)
{
// Your user prompt for days code goes here
if (days <= 0 || days > 10) {
JOptionPane.showMessageDialog(null, "Error, Please enter a number between 1 and 10");
exit = false; // This is not necessary but nice for readability's sake
}
else {
exit = true;
}
}
添加回答
舉報