car*_*azo 1 java for-loop if-statement break
因此,对于课堂作业,我必须接受用户输入并指定我的沙鼠对象每天可以使用的"食物"量.在这种情况下,我已经每天从用户那里获取最大量的食物,并且如果他们试图输入高于每日最大值的值,则需要向用户发出错误消息.
如果是这种情况,则需要重新提示他们输入沙鼠吃的食物量.
我似乎无法弄清楚如何打破"if"语句并回到"for"循环的顶部.这是我的代码:
for (int j = 0; j < numberOfFoods; j++) {
System.out.println(gerbilId[index].substring(index)
+ " eats how many " + foodNames[j] + "s per day");
int amountOfFood = keyboard.nextInt();
if (amountOfFood > foodMax[j]) {
System.out.println("Error. Please input a valid amount of food");
break;
} else {
gerbilConsumption[index] = amountOfFood;
}
}
Run Code Online (Sandbox Code Playgroud)
说使用的答案continue是错误的,因为它们不是你在这种情况下所寻找的.continue将您带到下一个食物类型,但如果输入无效,您希望保持同一个.您需要做的j--;是再次使用该号码
if (amountOfFood > foodMax[j]) {
System.out.println("Error. Please input a valid amount of food");
j--;
} else {
gerbilConsumption[index] = amountOfFood;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
197 次 |
| 最近记录: |