[英]The simple way to get int array from System.in in Java
The user types in System.in this用户在 System.in 中键入
1 2 3 4 44 50 and so on
I need to get int array from it, so my solution is:我需要从中获取 int 数组,所以我的解决方案是:
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String tempString = in.nextLine();
int tempArray[] = tempString.split(" ");
result[] = tempArray(tempArray.length);
for(int i=0; i<result.length; i++)
{
result[i] = Integer.parseInt(tempArray[i]);
}
}
}
Is there a way to simplify the code?有没有办法简化代码?
使用Stream
可以在一行中完成:
int[] arr = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
List<Integer> integersList = Stream.of("1 2 3 4 44 50".split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());
Also it can be usefull to remove redundant spaces删除多余的空间也很有用
List<Integer> integersList = Stream
.of("1 2 3 4 44 50".trim().replaceAll(" +", " ").split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.