Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring letters when parsing a double from a line in a file

I am trying to import some data from a file line by line. One specific line I was to read from may or may not have "kB" (kiloBytes) at the end and I want to parse the double that is in this line but my program gives me java.lang.NumberFormatException.

    while(inputStream.hasNextLine())
    {
        inputStream.nextLine(); // Skips a line between each object
        String sn = inputStream.nextLine();
        String sa = inputStream.nextLine();
        double ss = Double.parseDouble(inputStream.nextLine()); // This is where the problem occurs
        int sd    = Integer.parseInt(inputStream.nextLine());
        addSong(sn, sa, ss, sd); // Send the four variables for Song() to the addSong method
    }
    inputStream.close();

I have a feeling I could work with indexOf() here but I'm not sure how.

Cheers!

like image 960
Norsk Avatar asked Jan 13 '23 07:01

Norsk


2 Answers

double ss = Double.parseDouble(inputStream.nextLine().replaceAll("[a-zA-Z]", ""));

This will help you remove all characters from A-Z regardless of cases.

like image 132
Michael 'Maik' Ardan Avatar answered Jan 21 '23 21:01

Michael 'Maik' Ardan


If you just want to remove "kB", you can try the following :

String line = inputStream.nextLine();
line = line.replaceFirst("kB", "");
double ss = Double.parseDouble(line);

If you want to remove everything that can't be parsed by parseDouble, you have to use a regexp :

String line = inputStream.nextLine();
line = line.replaceAll("[^-\\d.]", "");
double ss = Double.parseDouble(line);

This regexp remove everything that is not :

  • a digit (you may want to use 0-9 instead of \\d if you are not interested in matching UTF-8 numbers)
  • or a dot (used for the decimal part)
  • or a minus sign (used for negative numbers).
like image 29
Florent Bayle Avatar answered Jan 21 '23 21:01

Florent Bayle