在Java中将字符串解析为双精度时出现错误。

huangapple go评论162阅读模式
英文:

An error when parsing a string to double in Java

问题

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

            // 进行其他操作
        }
    }
}

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

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

请注意,文件没有标题行。文件以无标题的值开头。我得到的错误是:

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'm trying to read a csv file and convert its String values to double.

public void trq() throws IOException, ParseException {
	Test4 obj = new Test4();
	String path = &quot;transposedData1.csv&quot;;
	BufferedReader readerBuffer = new BufferedReader(new FileReader(path));
	String line;
	List&lt;Double&gt; results = new ArrayList&lt;Double&gt;();
	while ((line = readerBuffer.readLine()) != null) {
		if(!line.contains(&quot;NA&quot;)) {
			ArrayList&lt;String&gt; data_per_class = convertCSVtoArrayList11(line);
			
			List&lt;Double&gt; doubleList = data_per_class.stream()
					.map(Double::parseDouble)
					.collect(Collectors.toList()); // the error here
			
			// do other things
		}
	}
}

public static ArrayList&lt;String&gt; convertCSVtoArrayList11(String pathCSV) {
	ArrayList&lt;String&gt; result = new ArrayList&lt;String&gt;();

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

	return result;
}

The CSV file looks like:

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. The file starts with values with no headers. The error I am getting is:

Exception in thread &quot;main&quot; java.lang.NumberFormatException: For input string: &quot;&quot;1.0&quot;&quot;
	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?

答案1

得分: 2

替换:

pathCSV.split(&quot;\\s*,\\s*&quot;);

为:

pathCSV.split(&quot;\\s+&quot;);

这样数字将在空格上进行分割。目前,它们被存储在结果中,带有额外的 &quot;,例如 &quot;&quot;1.0&quot;&quot;,应该存储为 &quot;1.0&quot;

英文:

Replace

pathCSV.split(&quot;\\s*,\\s*&quot;);

with

pathCSV.split(&quot;\\s+&quot;);

So that the numbers are split on spaces. Currently, they are getting stored into result with extra &quot; e.g. &quot;&quot;1.0&quot;&quot; which should be stored as &quot;1.0&quot;.

答案2

得分: 0

根据您所看到的错误消息,实际上可以看出该数字被一对引号包围,这可能导致调用失败。

一个快速的解决方法是使用 asString = substring(1, asString.length() - 2);,其中 asString 是您想要解析为双精度浮点数的字符串。

英文:

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);, with asString being the string that you want to parse to a double.

答案3

得分: 0

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

英文:

Use result.add(splitData[i].trim(). replaceAll(&quot;/&quot;&quot;,&quot;&quot;) ) before returning

huangapple
  • 本文由 发表于 2020年4月6日 01:43:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/61046805.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定