Java:将字符串解析为双精度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1418524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 16:28:50  来源:igfitidea点击:

Java: Parsing a string to a double

javaarraysstringfile

提问by Nick

I'm reading a file into an array and trying to take out the numbers and put them as a double in an array of their own. And apparently my middle name must be "Error". From what I can tell the code is ok....at least theres nothing jumping out at me. Here it is in all it's glory.

我正在将一个文件读入一个数组并尝试取出数字并将它们作为双精度放入它们自己的数组中。显然我的中间名必须是“错误”。据我所知,代码没问题……至少没有什么让我跳出来的。这是它的全部荣耀。

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.lang.Object.*;

public class ReadFromFile {
    public static void main (String[] args){
        File file = new File("vector10.txt");
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;
        StringBuffer sb = new StringBuffer();
        String string = new String();

        try{
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);


            while((string=dis.readLine()) != null){
                sb.append(string+"\n");
            }

            fis.close();
            bis.close();
            dis.close();

            System.out.println(sb);
            String newString = sb.toString();
            System.out.println(newString);
            String[] doubles = newString.split(",");
            for (int i=0; i<doubles.length; i++){
                System.out.println(doubles[i]);
            }

            Double arrDouble[] = new Double[doubles.length];

            int idx = 0;
            for(String s : doubles) {
               arrDouble[idx++] = Double.parseDouble(s); 
            }           

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

It keeps throwing an error

它不断抛出错误

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Long.parseLong(Long.java:412)
at java.lang.Long.parseLong(Long.java:461)
at ReadFromFile.main(ReadFromFile.java:51)

Programming is not necessarily my strong point and my eyes are starting to bleed looking at the screen. Any thoughts or tips are gratefully appreciated. Cheers

编程不一定是我的强项,看着屏幕,我的眼睛开始流血。非常感谢任何想法或提示。干杯

回答by Denis Tulskiy

If your file is comma separated then it's better to use Scanner

如果您的文件以逗号分隔,那么最好使用 Scanner

String doubles = "1.25,    1.65, 1.47";

Scanner f = new Scanner(doubles);
f.useLocale(Locale.US); //without this line the program wouldn't work 
                        //on machines with different locales
f.useDelimiter(",\s*");

while (f.hasNextDouble()) {
   System.out.println(f.nextDouble());
}

回答by Gothmog

Maybe you can try using Scanner class?

也许您可以尝试使用 Scanner 类?

Scanner sc = new Scanner(new File("vector10.txt"));
ArrayList<Double> lst = new ArrayList<Double>();
while (sc.hasNextDouble()) {
  lst.add(new Double(sc.nextDouble()));
}

回答by Thomas Padron-McCarthy

Your code doesn't seem to be the one actually run, but in your code, you are building a big string of all your numbers, separated by newlines. But then you split it (using String.split) at commas, and there are no commas in that string. So Double.parseDouble gets all the numbers at once.

您的代码似乎不是实际运行的代码,但是在您的代码中,您正在构建一个由换行符分隔的所有数字的大字符串。但是随后您将它拆分(使用 String.split)以逗号分隔,并且该字符串中没有逗号。所以 Double.parseDouble 一次获取所有数字。

回答by Yishai

The error says that you are calling Long.parseLong(), not Double.parseDouble(), as the code you posted says. Perhaps you forgot to recompile?

该错误表明您正在调用 Long.parseLong(),而不是 Double.parseDouble(),正如您发布的代码所说。也许你忘记重新编译?

That could be the whole problem, but if not send a System.out.println(string) of the value you are going to call Double.parseDouble(string) right before so you can see the value it fails on.

这可能是整个问题,但如果不发送值的 System.out.println(string) ,您将在之前调用 Double.parseDouble(string) 以便您可以看到它失败的值。

回答by Guss

Double.parseDouble()like all parse*methods do not react well to characters that they don't expect, and that - unfortunately - includes white space. A few spaces in your string can ruin your whole day.

Double.parseDouble()就像所有parse*方法都不能对他们不期望的字符做出很好的反应,而且 - 不幸的是 - 包括空格。字符串中的几个空格可能会毁了你一整天。

To solve, first it will be a good idea to spliton spaces as well, so something like newString.split("[,\\s]+")would work nicely by splitting and removing any sequence of white-space and/or commas. Then when you try to parse, trimyour string - just for safety - something like Double.parseDouble(doubles[i].trim()). For extra safety, check if your trimmed string is not the empty string before parsing - maybe something like if (doubles[i].trim().length() < 1) continue;.

要解决这个问题,首先split在空格上也是一个好主意,因此newString.split("[,\\s]+")通过拆分和删除任何空格和/或逗号序列,类似的东西可以很好地工作。然后,当您尝试解析时,trim您的字符串 - 只是为了安全 - 类似于Double.parseDouble(doubles[i].trim()). 为了更加安全,请在解析之前检查修剪后的字符串是否不是空字符串 - 可能类似于if (doubles[i].trim().length() < 1) continue;.

Good luck.

祝你好运。