如何从Java中的标准输入读取整数数组? [英] How to read array of integers from the standard input in Java?
问题描述
在从标准输入一行我有3种类型的整数:第一个整数ID,第二个整数N - 一些号码,后跟随N个整数,用一个空格separeted我想存储在数组或ArrayList中。我怎样才能做到这一点使用的BufferedReader?我有以下的code:
BR的BufferedReader =新的BufferedReader(新的InputStreamReader(System.in));
。字符串[]行= br.readLine()分裂();
INT ID =的Integer.parseInt(行[0]);
INT N =的Integer.parseInt(行[1]);
我的问题是是否有读取行的其余部分并将其存储到数组?任何优雅的方式
我怎样才能做到这一点使用的BufferedReader?
块引用>您已经阅读/分割线,这样你就可以刚过输入整数其余循环,并将其添加到一个数组:
INT []数组=新的INT [n]; //输入休息断言line.length + 2 == N; //或一些其它等效的校验的for(int i = 0; I< N;我++)
阵列[I] =的Integer.parseInt(行第[i + 2]);这也将让你在循环中处理错误(我会留给一部分,你,你应该觉得有必要)。
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?
解决方案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).
这篇关于如何从Java中的标准输入读取整数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!