使用hasNextInt语句时在while循环中排序



我刚开始学习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 cijfer = input.nextInt();时,扫描仪会立即提取你写的号码,并将其添加到列表中。循环将再次调用input.hasNextInt(),它将在打印文本之前请求另一个号码

要修复它,可以将获得输入的代码移动到循环的顶部。像这样:

while(input.hasNextInt()) {
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++;
}
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");
}
}

PS。当您退出此处的循环时,counter变量将是一次性的。你可以自己解决;(

相关内容

  • 没有找到相关文章

最新更新