将用空格分隔的整数读入 int[] 数组 [英] Read integers separated with whitespace into int[] array
问题描述
我用
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
reader.readLine();
示例输入是
1 4 6 32 5
读取输入并将其放入整数数组 int[]
的最快方法是什么?
What is the fastest way to read the input and put it into an integer array int[]
?
如果可能,我也在寻找一些单一的解决方案.
I'm also looking for some one-line solution if possible.
推荐答案
你可以使用Scanner
:
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNextInt())
list.add(scanner.nextInt());
int[] arr = list.toArray(new int[0]);
直到我们在 Java 中有闭包,这可能是你能得到的最短的.
Until we have closures in java, this is probably the shortest you can get.
int[] arr = list.toArray(new int[0]);
不起作用,因为没有从整数到整数的转换.不能将 int 用作泛型的类型参数.
int[] arr = list.toArray(new int[0]);
won't work because there's no conversion from Integer to int. You can't use int as a type argument for generics.
但是是的,如果您使用的是 Java 8,那么您可以通过以下代码片段(更好的处理方式)使用 Stream API.
But yeah If you are working with Java 8 then you can use Stream API for it with the below code snippet(Better way of doing things).
int[] array = list.stream().mapToInt(i->i).toArray();
这篇关于将用空格分隔的整数读入 int[] 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!