How to read array of integers from the standard input in Java?

核能气质少年 提交于 2019-12-01 14:28:48

Use Scanner and method hasNextInt()

Scanner scanner = new Scanner(System.in);

while (scanner.hasNext()) {

     if (scanner.hasNextInt()) {
        arr[i]=scanner.nextInt();
        i++;
     }
  }

How can I do this using BufferedReader?

You've already read/split the line, so you can just loop over the rest of the inputted integers and add them to an array:

int[] array = new int[N];  // rest of the input

assert line.length + 2 == N;  // or some other equivalent check

for (int i = 0; i < N; i++)
    array[i] = Integer.parseInt(line[i + 2]);

This will also let you handle errors within the loop (I'll leave that part to you, should you find it necessary).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!