简体   繁体   English

JAVA如何按空间拆分并存储为双数组

[英]JAVA How to split by space and store into double array

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

You should read the line of from the file as a String, split that and convert to double. 您应该将文件中的行作为字符串读取,将其拆分并转换为双精度。 Try this: 尝试这个:

    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();
    }

I also added a bit to remove the first element since is not a double . 我还添加了一些内容来删除第一个元素,因为它不是double You could condense the two for-loops together, avoiding having a separate x-array. 您可以将两个for循环压缩在一起,避免使用单独的x数组。 This can be done as follows: 可以按照以下步骤进行:

        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]);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM