Skip to content
Advertisement

How to solve infinite readLine while

I have a program and one of the methods I use is for counting the lines a .txt file has and return an integer value. The problem is when I execute it, despite I wrote if my line is == null the while has to stop, the while loop keeps going, ignoring the nulls it gets infinitely.

I don’t know what to do to try to solve it.

JavaScript

It has to stop when it detects a null, which means there are no more lines, but it keeps going.

Advertisement

Answer

When you instantiate a BuffereReader assign it to count, count will always be non-null and hence will satisfy the while loop:

JavaScript

Instead use the following code, where the each line will be read and checked whether it is null, if null then the program will exit.:

JavaScript

If you are using JDK-1.8 you can shorten your code using the Files API:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement