Ignoring letters when parsing double from line in file

I am trying to import some data from a file line by line. One particular line that I had to read may or may not have β€œkB” (kilobytes) at the end, and I want to parse the double that is on that 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 that I can work with indexOf () here, but I'm not sure how to do it.

Hooray!

+4
source share
3 answers

Just cross out all numbers or digits from the line as you read it, using replaceAll("[^\\d.]", "") :

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

This keeps it on one line.

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

This will help you remove all characters from AZ, regardless of the case.

+4
source

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 cannot be parsed using parseDouble , you need to use regexp:

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

This regular expression removes everything that is not:

  • digit (you can use 0-9 instead of \\d if you are not interested in UTF-8 numbers)
  • or period (used for decimal)
  • or minus sign (used for negative numbers).
+3
source

Source: https://habr.com/ru/post/1482493/


All Articles