Tech Bandit Tech Bandit - 10 months ago 51
Java Question

NumberFormatException error from reading a file

I've been getting a

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
. 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++) {

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

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

//Read Whole File
BufferedReader br2 = new BufferedReader(fr);
while((str = br.readLine()) != null) {
} 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.


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();

    totalBalNum = Double.parseDouble(holderStr);