Search code examples
javawhile-loopvariable-assignmentbufferedreader

Assigning values in the predicate of a while loop - BufferedReader


I have a piece of code that looks like this:

public void cinemaFromFile(String fileName) throws IOException {

    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String line;
    while ((line = reader.readLine()) != null) {

        if (line.equals("Movies")) {

            while ((line = reader.readLine()) != null 
                    && !line.equals("Theaters")) {

                String currentline = line; 
                String[] parts = currentline.split(":");
                String part1 = parts[0]; 
                String part2 = parts[1]; 
                movies.add(new Movie(part1, part2));
            }
        }

    reader.close();
}

As you can see, I assign line a value in the termination clause of the while loop.

I am new to BufferedReaders and I am looking for an alternative to this. IE, I want to have the assignment statement("line = reader.readLine()") in a separate statement, external to the while loop termination clause.

I have tried moving "line = reader.readLine()" into the body of the while loop but that doesn't work. I have also tried putting it right before the while loop, which also doesn't work.

I think I have fundamentally misunderstood how BufferedReaders work, can they only iterate through the lines in while loops?


Solution

  • To pull the assignment out of the while loop condition, you must understand that the while loop condition is evaluated once before the first iteration, and after the end of each iteration.

    You can emulate that by placing the assignment before the while loop even begins, and also adding it to the end of the while loop body.

    line = reader.readLine();
    while (line != null) {
        // Rest of body is untouched
    
        // Read again at the end.
        line = reader.readLine();
    }
    

    This will operate the same. It may even be a little clearer than having the assignment in the condition of the while loop, even if it's a little less concise.

    The BufferedReader does nothing special in this regard with while loops. It just returns null when readLine() is called and there's no input left.