Java 带有hasNextInt()的while循环完成,但程序在此之后不会执行任何操作

Java 带有hasNextInt()的while循环完成,但程序在此之后不会执行任何操作,java,java.util.scanner,Java,Java.util.scanner,我这里有一个程序: ArrayList<Integer> meh = new ArrayList<Integer>(); Scanner sc = new Scanner(System.in); System.out.print("Input 3 numbers: "); while (sc.hasNextInt()) { meh.add(sc.nextInt()); System.out.println("meeeeeep"); } System.o

我这里有一个程序:

ArrayList<Integer> meh = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
System.out.print("Input 3 numbers: ");

while (sc.hasNextInt()) {
    meh.add(sc.nextInt());
    System.out.println("meeeeeep");
}

System.out.println("Goodbye");

它不会打印“再见”消息,也不会执行我在其后面添加的任何操作。

这是因为扫描仪正在等待即将到来的输入
sc.hasNextInt()
正在等待下一个令牌并确定它是否为int

要解决此问题,请尝试使用
String.split()按行读取并在
上拆分“

另一种解决方案可能是在for循环中执行此操作:

for (int i = 0; i < 3; ++i) {
    meh.add(sc.nextInt());
    System.out.println("meeeeeep");
}
for(int i=0;i<3;++i){
meh.add(sc.nextInt());
System.out.println(“meeeeeep”);
}

这是因为扫描仪正在等待即将到来的输入
sc.hasNextInt()
正在等待下一个令牌并确定它是否为int

要解决此问题,请尝试使用
String.split()按行读取并在
上拆分“

另一种解决方案可能是在for循环中执行此操作:

for (int i = 0; i < 3; ++i) {
    meh.add(sc.nextInt());
    System.out.println("meeeeeep");
}
for(int i=0;i<3;++i){
meh.add(sc.nextInt());
System.out.println(“meeeeeep”);
}

如果您知道需要多少个整数,就不需要while循环。for循环解决方案要好得多。另一种解决方案是读取文件或管道输入。如果您知道需要多少个整数,则不需要while循环。for循环解决方案要好得多。另一种解决方案是从文件读取或管道化输入。