如何从 Java 的标准输入中读取整数数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24517251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:41:47  来源:igfitidea点击:

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

javaarraysbufferedreader

提问by sammy333

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:

在标准输入的一行中,我有 3 种类型的整数:第一个整数是 id,第二个整数是 N - 某个数字,然后是 N 个整数,由我想存储在数组或 ArrayList 中的单个空格分隔. 如何使用 BufferedReader 执行此操作?我有以下代码:

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?

我的问题是有没有什么优雅的方法来读取该行的其余部分并将其存储到数组中?

回答by Jerky

Use Scannerand method hasNextInt()

用途Scanner及方法hasNextInt()

Scanner scanner = new Scanner(System.in);

while (scanner.hasNext()) {

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

回答by arshajii

How can I do this using BufferedReader?

如何使用 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).

这也可以让您处理循环中的错误(如果您觉得有必要,我会将这部分留给您)。