简体   繁体   English

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

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

How to scan an indefinite list of numbers from a single input? 如何从单个输入中扫描不确定的数字列表?

I did a brief google search and found hasNextInt(), but it only stops scanning if the last input is NOT an integer, while I need it to stop if it's the last integer. 我做了一个简短的谷歌搜索,发现hasNextInt(),但是它仅在最后一个输入不是整数的情况下才停止扫描,而如果它是最后一个整数则需要停止扫描。 For example, it will continue to ask me if my list ends with an integer. 例如,它将继续询问我列表是否以整数结尾。

My code: 我的代码:

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

You may use hasNext() instead. 您可以使用hasNext()代替。 Then parse the input and get the number - 然后解析输入并获取数字-

    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
        }
   }

Now if the input not is an integer then it will not stop. 现在,如果输入的不是整数,它将不会停止。 Rather it will go for the catch block. 相反,它将用于catch块。 And since the catch block is still in the while loop so you can take a new input still now. 并且由于catch块仍处于while循环中,因此您现在仍可以接受新的输入。

Hope it will help. 希望它会有所帮助。
Thanks a lot 非常感谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM