How to read array of integers from the standard in

2019-02-21 02:22发布

问题:

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