如何从单个输入扫描不确定的数字列表?

How to scan an indefinite list of numbers from a single input?

如何从单个输入中扫描不确定的数字列表?

我做了一个简短的 google 搜索并找到了 hasNextInt(),但它只会在最后一个输入不是整数时停止扫描,而如果它是最后一个整数我需要它停止。例如,它会继续询问我的列表是否以整数结尾。

我的代码:

 System.out.println("Enter a list of numbers");
        int n = 0;
        while (input.hasNextInt()){
            n = input.nextInt();
            List.push(n);
        }
        List.displayStack();

您可以改用hasNext()。然后解析输入并得到数字 -

    int n=0;
    Scanner input = new Scanner(System.in);

    while (input.hasNext()) {
        try {
            n = Integer.parseInt(input.nextLine());
            //do something eg.- you have done
            //List.push(n);
        } catch (NumberFormatException nfe) { 
            //handle exception
        }
   }

现在如果输入不是整数那么它就不会停止。相反,它将用于 catch 块。由于 catch 块仍在 while 循环中,因此您现在仍然可以接受新的输入。

希望对您有所帮助。
非常感谢