Tech Bandit Tech Bandit - 3 months ago 10
Java Question

NumberFormatException error from reading a file

I've been getting a

NumberFormatException
error when I try to read some data from a text file and convert it to an integer. From what I've seen other people say, this error is caused when an empty string is converted to an integer using
pasreInt()
. But I've been able to print the string '1' from the file into the output. Does anyone know why I'm getting this error even though the string doesn't seem to be empty? Here's my code:

try {
//Retrieve Info
FileReader fr = new FileReader("BankInfo.txt");
BufferedReader br = new BufferedReader(fr);
//Skip specified number of lines
for(int i=0; i<line; i++) {
br.readLine();
}

//Print the string to output
String holderStr = br.readLine();
System.out.println(holderStr);

//The line creating the NumberFormatException
totalBalNum = (double)Integer.parseInt(holderStr);

br.close();
//Read Whole File
BufferedReader br2 = new BufferedReader(fr);
while((str = br.readLine()) != null) {
arrList.add(str);
}
br2.close();
} catch (IOException | NumberFormatException e) {
System.out.println("ERROR! Problem with FileReader. " + e);
}


I know my code is probably really sloppy and inefficient too... I'm a little bit of a noob.

Answer

Ok, I think converting string into Integer and then typecasting it to double is causing the error. Why don't you just convert the string to double. Also you must trim the line while reading it to avoid any spaces.

    String holderStr = br.readLine().trim();
    System.out.println(holderStr);

    totalBalNum = Double.parseDouble(holderStr);