我需要帮助验证输入。我有一个程序,可以根据用户的输入处理学生的成绩。如果有人输入低于0或高于100的分数,我希望这个循环重新开始。这是我到目前为止所知道的:
double scores[] = new double[size];
for (int i = 0;i<= scores.length-1;i++)
{
System.out.print("\n\nScore number " + (i+1) + ": ");
scores[i] = sc.nextInt();
}
System.out.println("Here are your scores: " + Arrays.toString(scores));
我对如何实现无效检查器感到困惑。我知道这与while循环有关。例如当值为0时,如果有人输入无效答案,则答案将从0更改。但我不确定我到底该怎么做,或者是否有更好的方法来感谢任何帮助。谢谢
发布于 2017-11-03 16:52:12
您可以使用嵌套的while循环和条件语句来执行以下操作:
for (int i = 0;i< scores.length;i++){
while(true){
System.out.print("\n\nScore number " + (i+1) + ": ");
int score = sc.nextInt();
if(score >= 0 && score <=100){
scores[i] = score;
break;
}else{
System.out.println("Error: score entered is outside allowable range");
System.out.println("Please try again");
continue;
}
}
}
发布于 2017-11-03 16:54:06
您可以简单地要求用户重新输入输入错误的分数的值。
double scores[] = new double[size];
for (int i = 0; i<= scores.length-1; i++)
{
System.out.print("\n\nScore number " + (i+1) + ": ");
scores[i] = sc.nextInt();
if(scores[i] < 0 || scores[i] > 100) {
i -= 1;
continue;
}
}
发布于 2017-11-03 17:33:32
我对如何实现无效的检查器感到困惑。我知道这与while循环有关。
do-while
循环在输入验证中是首选的,因为它允许首先接收输入,然后检查它是否通过了要求。如果输入无效,请重复输入。
for(int i=0; i<scores.length; i++){
do{
System.out.print("\n\nScore number " + (i+1) + ": ");
input = sc.nextInt();
}while(input < 0 || input > 100);
scores[i] = input;
}
for-循环和do-while循环用于不同的目的。因此,请不要被
循环的,它只负责接收数组的多个输入,
- while循环,它只负责验证每一个输入。
https://stackoverflow.com/questions/47100378
复制相似问题