How to read multiple Integer values from a single line of input in Java?

后端 未结 17 1367
天涯浪人
天涯浪人 2020-11-27 03:16

I am working on a program and I want to allow a user to enter multiple integers when prompted. I have tried to use a scanner but I found that it only stores the first intege

17条回答
  •  -上瘾入骨i
    2020-11-27 03:42

    Try this

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in); 
        while (in.hasNext()) {
            if (in.hasNextInt())
                System.out.println(in.nextInt());
            else 
                in.next();
        }
    }
    

    By default, Scanner uses the delimiter pattern "\p{javaWhitespace}+" which matches at least one white space as delimiter. you don't have to do anything special.

    If you want to match either whitespace(1 or more) or a comma, replace the Scanner invocation with this

    Scanner in = new Scanner(System.in).useDelimiter("[,\\s+]");
    

提交回复
热议问题