将用空格分隔的整数读入 int[] 数组 [英] Read integers separated with whitespace into int[] array

查看:20
本文介绍了将用空格分隔的整数读入 int[] 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆