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

烈酒焚心 提交于 2019-12-04 02:32:11

问题


in one line from the standard input I have 3 types of integers: the first integer is id, the second integer is N - some number, and after that follows N integers, separeted by a single space which I want to store in array or ArrayList. How can I do this using BufferedReader? I have the following code:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
int ID = Integer.parseInt(line[0]);
int N = Integer.parseInt(line[1]);

My question is is there any elegant way to read the rest of the line and to store it into array?


回答1:


Use Scanner and method hasNextInt()

Scanner scanner = new Scanner(System.in);

while (scanner.hasNext()) {

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



回答2:


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).



来源:https://stackoverflow.com/questions/24517251/how-to-read-array-of-integers-from-the-standard-input-in-java

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