How to use .nextInt() and hasNextInt() in a while loop

后端 未结 3 2091
礼貌的吻别
礼貌的吻别 2020-11-29 12:51

So I want my program to read an input, which has some integers in one line, for example:

1 1 2

Then it should read every integer separately and print it in a

3条回答
  •  鱼传尺愫
    2020-11-29 13:20

    If you like to stop your loop after the line, create your Scanner like this:

    public static void main(final String[] args) {
        Scanner scan = new Scanner(System.in).useDelimiter(" *");
        while (scan.hasNextInt() && scan.hasNext()) {
            int x = scan.nextInt();
            System.out.println(x);
        }
    
    }
    

    The trick is to define a delimiter that contains whitespace, the empty expression, but not the next line character. This way the Scanner sees the \n followed by a delimiter (nothing) and the input stops after pressing return.

    Example: 1 2 3\n will give the following tokens: Integer(1), Integer(2), Integer(3), Noninteger(\n) Thus the hasNextInt returns false.

提交回复
热议问题