user7500403
user7500403

Reputation:

Parsing String read from a text file to Integer

I have a simple program where i read from a text file. Text file contains a number 99. I read this number using a method named readFile. After reading it, i then call writeFile method which increments the number read from the text file by 1 and the again saves it in the text file.

Method to read from file

public void readFile() {

    String line = "";

    try(FileReader fr = new FileReader("Room Number.txt"); 
        BufferedReader br = new BufferedReader(fr)) {

       while((line = br.readLine()) != null) {
           roomNumberField.setText(line);
       }
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    writeFile(line);
}

Problem

As you can see in the above method, i am reading the data from file in a String variable line and at the end of the method, i call writeFile method and pass the line variable in to this method. In the writeFile method, before i can increment the line variable by 1, i have to parse it as int but doing so throws NumberFormatException. Now in my case, this exception will only be thrown only if line cannot be parsed as an int. At first i thought it could be because of line variable containing any space, so i called trim method on it which then threw NullPointerException which led me to believe that line is null.

Question is, why is line variable null ? it is initialized in while loop so how can it be null at the end of the method ?

PS. Number is read from the file correctly and if i move writeFile(line); inside while loop of readFile method, it doesn't throws any exception and my program works as it should.

Upvotes: 0

Views: 118

Answers (2)

captainchhala
captainchhala

Reputation: 825

answer is simple when line get equals to null in

while((line = br.readLine()) != null) {

while loop breaks and line has null value at this spot outside the loop. while inside the loop line has always some values because it is inside the loop :).

Upvotes: 1

twain249
twain249

Reputation: 5706

Couple of things. Your call to writeFile() should be inside the try block since there is no point in running it if the read fails.

Also your error is because

while((line = br.readLine()) != null) {
           roomNumberField.setText(line);
       }

This loop runs until line == null. So after it exits (before calling writeFile()) the value will be null.

Either you want to write every line then writeFile should be in the loop or you need to figure out which line you want and save it.

Upvotes: 3

Related Questions