简体   繁体   English

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

[英]Java: Parsing a string to a double

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. 我正在将文件读取到数组中,并尝试取出数字并将它们作为自己数组中的double放置。 And apparently my middle name must be "Error". 而且显然我的中间名必须是“ 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 干杯

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

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

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. 但是然后您将其分割(使用String.split),并以逗号分隔,并且该字符串中没有逗号。 So Double.parseDouble gets all the numbers at once. 因此Double.parseDouble一次获取所有数字。

The error says that you are calling Long.parseLong(), not Double.parseDouble(), as the code you posted says. 该错误表明您正在调用Long.parseLong(),而不是Double.parseDouble(),就像您发布的代码所说的那样。 Perhaps you forgot to recompile? 也许您忘记了重新编译?

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),这样您就可以看到失败的值。

Double.parseDouble() like all parse* methods do not react well to characters that they don't expect, and that - unfortunately - includes white space. 像所有parse*方法一样, Double.parseDouble()对它们不期望的字符的反应也不好,不幸的是,它包含空格。 A few spaces in your string can ruin your whole day. 字符串中的一些空格会破坏您的一整天。

To solve, first it will be a good idea to split on spaces as well, so something like newString.split("[,\\\\s]+") would work nicely by splitting and removing any sequence of white-space and/or commas. 为了解决这个问题,首先也要在空格上进行split ,因此像newString.split("[,\\\\s]+")这样的方法可以通过拆分和删除任何空白和/或空格来很好地工作。逗号。 Then when you try to parse, trim your string - just for safety - something like Double.parseDouble(doubles[i].trim()) . 然后,当您尝试解析时,为安全起见, trim字符串Double.parseDouble(doubles[i].trim())类似于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; 为了提高安全性,请在分析之前检查修剪后的字符串是否不是空字符串-可能类似于if (doubles[i].trim().length() < 1) continue; .

Good luck. 祝好运。

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

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