简体   繁体   中英

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. 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

If your file is comma separated then it's better to use 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 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. So Double.parseDouble gets all the numbers at once.

The error says that you are calling Long.parseLong(), not Double.parseDouble(), as the code you posted says. 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.

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.

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. Then when you try to parse, trim your 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; .

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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