简体   繁体   English

在 Java 中将字符串解析为 double 时出错

[英]An error when parsing a string to double in Java

I'm trying to read a csv file and convert its String values to double.我正在尝试读取 csv 文件并将其字符串值转换为双精度值。

public void trq() throws IOException, ParseException {
    Test4 obj = new Test4();
    String path = "transposedData1.csv";
    BufferedReader readerBuffer = new BufferedReader(new FileReader(path));
    String line;
    List<Double> results = new ArrayList<Double>();
    while ((line = readerBuffer.readLine()) != null) {
        if(!line.contains("NA")) {
            ArrayList<String> data_per_class = convertCSVtoArrayList11(line);

            List<Double> doubleList = data_per_class.stream()
                    .map(Double::parseDouble)
                    .collect(Collectors.toList()); // the error here

            // do other things
        }
    }
}

public static ArrayList<String> convertCSVtoArrayList11(String pathCSV) {
    ArrayList<String> result = new ArrayList<String>();

    if (pathCSV != null) {
        String[] splitData = pathCSV.split("\\s*,\\s*");
        for (int i = 0; i < splitData.length; i++) {
            if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
                result.add(splitData[i].trim());
            }
        }
    }

    return result;
}

The CSV file looks like: CSV 文件如下所示:

1.0  8.0  4.0  6.0
3.0  2.0  1.0  5.0
7.0  1.0  8.0  1.0
1.0  2.0  1.0  4.0

Note that there is no header.请注意,没有 header。 The file starts with values with no headers.该文件以没有标题的值开头。 The error I am getting is:我得到的错误是:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""1.0""
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:538)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:566)
    at Test4.trq(Test4.java:1063) \\ I mentioned that in the code above

Do you have any idea how to solve this?你知道如何解决这个问题吗?

Replace代替

pathCSV.split("\\s*,\\s*");

with

pathCSV.split("\\s+");

So that the numbers are split on spaces.这样数字就按空格分开。 Currently, they are getting stored into result with extra " eg ""1.0"" which should be stored as "1.0" .目前,它们被存储到结果中,带有额外的"例如""1.0"" ,应该存储为"1.0"

Based on the error message you can see, that the number is actually aurrounded by a pair of quotation marks, which probably causes the call to fail.根据您看到的错误消息,该数字实际上是用一对引号引起来的,这可能导致调用失败。

A quick fix would be to use asString = substring(1, asString.length() - 2);一个快速的解决方法是使用asString = substring(1, asString.length() - 2); , with asString being the string that you want to parse to a double. ,其中asString是您要解析为双精度的字符串。

Use result.add(splitData[i].trim(). replaceAll("/"","") ) before returning在返回之前使用result.add(splitData[i].trim(). replaceAll("/"","") )

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

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