【问题标题】:JAVA How to split by space and store into double arrayJAVA如何按空间分割并存储成双数组
【发布时间】:2018-02-19 05:03:48
【问题描述】:

如何从文本文件中读取数据,将每个单词/数字拆分并存储到数组中?

【问题讨论】:

  • Arrays.stream(str.split(" ")).skip(1).mapToDouble(Double::parseDouble).toArray();

标签: java arrays split


【解决方案1】:

您应该将文件中的行读取为字符串,将其拆分并转换为双精度。试试这个:

    try {
        Scanner scan = new Scanner(new File("path/to/file"));

        String str = scan.nextLine();

        String[] split = str.split("\\s+");

        // remove first element
        String[] x = new String[split.length-1];
        for (int i = 0; i < x.length; i++) {
            x[i] = split[i+1];
        }

        double[] numbers = new double[x.length];
        for (int i = 0; i < x.length; i++) {
            numbers[i] = Double.parseDouble(x[i]);
        }


    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

我还添加了一些内容来删除第一个元素,因为它不是double。您可以将两个 for 循环压缩在一起,避免使用单独的 x 数组。这可以按如下方式完成:

        String[] split = str.split("\\s+");

        // create double array while ignoring the first element 
        double[] numbers = new double[split.length-1];
        for (int i = 0; i < numbers .length; i++) {
            numbers[i] = Double.parseDouble(split[i+1]);
        }

【讨论】:

  • 真的不需要String[] x。只需加载正确大小的双精度数组
  • @TM00:您根本不需要 String[] x = ... 和 for 循环来删除第一个。只需忽略下一个 for 循环中将 string[] 转换为 double[] 的第一个元素。
  • @cricket_007 是的,我在答案中添加了一段额外的代码来展示如何做到这一点。
  • 为什么没有人使用 try-with-resources?
猜你喜欢
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
相关资源
最近更新 更多