不好意思,这个新问题,对Java来说是很新的。
因此,当用户输入超出界限(小于0,大于100)时,我想显示一条错误消息,这是我设法做到的,但我也希望用户可以再试一次,但是我的当前代码只会继续执行程序。
这就是我现在拥有的:
import java.util.Scanner;
public class storeQuota {
public static void main(String [] args) {
Scanner input = new Scanner (System.in);
int quotas [] = new int [100];
int NumberOfWorkers = 100;
for (int i = 0; i<numberOfWorkers; i++) {
if (i == 0) {
System.out.print("Enter the quota for the 1st student: ");
}
else if (i == 1) {
System.out.print("Enter the quota for the 2nd student: ");
}
else if (i == 2) {
System.out.print("Enter the quota for the 3rd student: ");
}
else if (i >= 3) {
System.out.print("Enter the quota for the " + (i+1) + "th student: ");
}
while (true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0)
System.out.println("Error - Can only be between 0 and 100.");
break;
}
}
//Printing all quotas.
System.out.println("Thank you for your input. Your entered quotas are: ");
for (int i=0; i<numberOfWorkers; i++)
{
System.out.print(quotas[i] + ", ");
}
input.close();
}
}使用此代码,当用户输入的int不是介于0到100之间但用户将无法再次尝试时,错误消息将被正确地显示出来,程序将继续请求下一个商。
发布于 2022-09-09 12:34:11
我想问题就在这条线上。
break;之后
System.out.println("Error - Can only be between 0 and 100.");它总是破坏while循环。相反,您只希望在输入处于有效范围内时中断while循环。我不会使用while(true),而是某种条件变量,如果输入在有效范围内,则在while循环中将其设置为false,这也是因为在我看来,while(true)不是一个很好的编程实践。
发布于 2022-09-09 13:00:49
您的问题是使用Break;而不是使用它,您应该将while(true)更改为while(false),您还忘记在if语句周围添加花括号。
boolean x = true;
while (x){
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0){
System.out.println("Error - Can only be between 0 and 100.");
x = false;
}
}此外,我建议学习异常,因为它们将使这10倍更容易。
发布于 2022-09-14 08:09:11
执行时,“中断”会中断当前所处的循环。在您的代码中,无论输入的结果是什么,中断都会被执行。
最简单的解决方案是(最接近原始代码):
while(true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0) {
System.out.println("Error - Can only be between 0 and 100.");
} else {
break;
}
}在这里,只有输入正确的输入,循环才会中断。
https://stackoverflow.com/questions/73662159
复制相似问题