mr_*_*ond 1 java arrays int system input
用户在 System.in 中键入
1 2 3 4 44 50 and so on
Run Code Online (Sandbox Code Playgroud)
我需要从中获取 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]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法简化代码?
使用Streams 可以在一行中完成:
int[] arr = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |