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

前端 未结 2 1454
心在旅途
心在旅途 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:15

    Use Scanner and method hasNextInt()

    Scanner scanner = new Scanner(System.in);
    
    while (scanner.hasNext()) {
    
         if (scanner.hasNextInt()) {
            arr[i]=scanner.nextInt();
            i++;
         }
      }
    
    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题