【问题标题】:The simple way to get int array from System.in in Java在 Java 中从 System.in 获取 int 数组的简单方法
【发布时间】:2020-04-04 09:20:15
【问题描述】:

用户在 System.in 中键入

1 2 3 4 44 50 and so on

我需要从中获取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]);
        }
    }
}

有没有办法简化代码?

【问题讨论】:

  • 您的代码没有通过编译 - tempArray 应该是 String 数组,而不是 int 数组。而tempArray(tempArray.length) 也没有通过编译。

标签: java arrays input int system


【解决方案1】:

使用Streams 可以在一行中完成:

int[] arr = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();

【讨论】:

    【解决方案2】:
    List<Integer> integersList = Stream.of("1 2 3 4 44 50".split(" "))
          .map(Integer::parseInt)
          .collect(Collectors.toList());
    

    删除多余的空格也很有用

    List<Integer> integersList = Stream
            .of("1 2 3 4 44 50".trim().replaceAll(" +", " ").split(" "))
            .map(Integer::parseInt)
            .collect(Collectors.toList());
    

    【讨论】:

    • 欢迎来到 Stack Overflow _ 一个“好的答案”还包括一两句话,以纯文本形式解释您认为您的解决方案可行的原因。请访问 SO 帮助中心,特别是本指南以获取更多详细信息 >>> stackoverflow.com/help/how-to-answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多