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

前端 未结 2 1453
心在旅途
心在旅途 2021-01-07 15:52

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

2条回答
  •  离开以前
    2021-01-07 16:27

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

提交回复
热议问题