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!
double ss = Double.parseDouble(inputStream.nextLine().replaceAll("[a-zA-Z]", ""));
This will help you remove all characters from A-Z regardless of cases.
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 :
0-9
instead of \\d
if you are not interested in matching UTF-8 numbers)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With