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

后端 未结 17 1422
天涯浪人
天涯浪人 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条回答
  •  孤街浪徒
    2020-11-27 03:21

    I use it all the time on hackerrank/leetcode

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String  lines = br.readLine();    
            
        String[] strs = lines.trim().split("\\s+");
                
        for (int i = 0; i < strs.length; i++) {
        a[i] = Integer.parseInt(strs[i]);
        }
    

提交回复
热议问题