【发布时间】:2018-07-23 08:21:44
【问题描述】:
我刚开始接触java。我正在尝试编写一个使用用户输入将数字添加到 ArrayList 的代码。我找到了一种运行 while 循环的方法,当我使用“hasNextInt”语句输入除数字以外的任何内容时该循环停止,但由于某种原因,它直接输入,然后才从第一个 if 语句中打印出消息。我做错了什么?
输出如下所示:
This program takes grades from 1 to 100
You may begin typing numbers now
To stop setting grades, type any word (like 'done')
Enter the 1st number:
68
54
Enter the 2nd number
94
Enter the 3rd number
这是我写的代码:
public static void main(String args[]){
Scanner input = new Scanner(System.in);
ArrayList<Integer> myClassroom = new ArrayList<Integer>();
GradeAnalyzer myAnalyzer = new GradeAnalyzer();
System.out.println("This program takes grades from 1 to 100");
System.out.println("You may begin typing numbers now");
System.out.println("To stop setting grades, type any word (like 'done') ");
int counter = 1;
System.out.println("Enter the 1st number:");
while(input.hasNextInt()) {
if (counter == 21 || counter == 31 || counter == 41 || counter == 51 || counter == 61) {
System.out.println("Enter the " + counter + "st" + " number");
} else if (counter == 2 ||counter == 22 ||counter == 32 ||counter == 42 ||counter == 52 ||counter == 62) {
System.out.println("Enter the " + counter + "nd" + " number");
} else if (counter == 3 ||counter == 23 ||counter == 33 ||counter == 43 ||counter == 53 ||counter == 63){
System.out.println("Enter the " + counter + "rd" + " number");
} else if (counter == 1) {
System.out.print("");
} else {
System.out.println("Enter the " + counter + "th" + " number");
}
int cijfer = input.nextInt();
if(cijfer < 0 || cijfer > 100) {
System.out.println("Please enter a number between 1 and 100.");
} else {
myClassroom.add(cijfer);
counter++;
}
}
System.out.println("You entered " + counter + " valid numbers.");
}
【问题讨论】:
-
hasNextInt() 阻塞,直到它知道是否有下一个 Int 。在您输入第二个数字之前,它无法返回任何内容。请注意,对于第一个数字,您如何打印消息,然后调用 hasNextInt()。对于第二个数字,你做相反的事情。
标签: java if-statement while-loop user-input