![](/img/trans.png)
[英]Using hasNextInt with do-while loop, no error message for negative integer
[英]Using do-while loop to send an error message when input is out of bounds
在这里,我使用 do while 循环来执行一个程序,该程序允许用户在一个数组中对学生的分数进行评分,然后将它们打印出来。 我正在努力实现一个系统,该系统在用户输入低于 0 或高于 100 的数字时发送错误消息,然后让用户重试。
导入 java.util.Scanner;
公共 class storeScore {
public static void main(String [] args) {
Scanner input = new Scanner (System.in);
int scores [] = new int [7];
int numberOfStudents = 7;
//User input all scores. For loop works by asking for user input until it reaches the number as input in numberOfStudents.
do
{
for(int i = 0; i<numberOfStudents; i++) {
scores[i] = input.nextInt();
if (i == 0) {
System.out.print("Enter the score for the 1st student: ");
}
else if (i == 1) {
System.out.print("Enter the score for the 2nd student: ");
}
else if (i == 2) {
System.out.print("Enter the score for the 3rd student: ");
}
else if (i >= 3) {
System.out.print("Enter the score for the " + (i+1) + "th student: ");
}
}
//Error output if input is incorrect
}
while (scores[i] < 0 || scores[i] > 100) {
System.out.println("Input out of bounds. Score can only be between 0 and 100");
}
//Printing all scores.
System.out.println("Thank you for your input. Your entered scores are: ");
for (int i=0; i<numberOfStudents; i++)
{
System.out.print(scores[i] + ", ");
}
input.close();
}
}
您在 while 循环中打印错误消息,而没有任何方法可以打破该循环。
首先尝试将用户的输入捕获为一个 int 变量,您可以在将其分配给 score[] 之前检查它是否有效。
for(int i = 0; i<numberOfStudents; i++) {
String message;
if (i == 0) {
message = "Enter the score for the 1st student: ";
}
else if (i == 1) {
message = "Enter the score for the 2nd student: ";
}
else if (i == 2) {
message = "Enter the score for the 3rd student: ";
}
else if (i >= 3) {
message = "Enter the score for the " + (i + 1) + " student: ";
}
System.out.println(message);
int score = input.nextInt();
//Now check if the input value is valid
while (score < 0 || score > 100) {
System.out.println("Input out of bounds. Score can only be between 0 and 100");
System.out.println(message);
score = input.nextInt();
}
score[i] = score;
}
现在,循环将为学生 i 打印消息,然后输入分数。 如果分数无效,while 循环将打印出错误消息,并重新输入。 如果这次输入有效,while 循环会中断并将新分数分配给学生 i,否则它会重新打印错误消息并再次接受输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.