Quick query here guys - I have a program that reads from a file and counts the number of lines in the code. This works fine but when I go to print the contents of the file to the screen or to a Dialog box the number of lines that the code seems to counts halves.

Here is the block of code for the reading:

while( ( myFile.readLine() ) != null )
			{
					// System.out.println( myFile.readLine() );
					fileLength++;
			}

When i uncomment the "out.println" line the fileLength is affected and it also only reads and prints to the screen every even numbered line. Why would this be?

Because each call to `readLine` bumps up/increments the file pointer, so as per your example, you effectively end up reading two lines in a single iteration. Declare a variable which would hold the string read and you should be good to go.

String str = null;
while((str = reader.readLine()) != null) {
  System.out.println(str);
  lineCount++;
}

Because each call to `readLine` bumps up/increments the file pointer, so as per your example, you effectively end up reading two lines in a single iteration. Declare a variable which would hold the string read and you should be good to go.

String str = null;
while((str = reader.readLine()) != null) {
  System.out.println(str);
  lineCount++;
}

Cheers mate, so to verify, the variable "str" basically holds the correct line being read from the program and, as long as it doesn't equal null, increments the lineCount and then passes the value of the next line to "str," and so on and so on?

Cheers mate, so to verify, the variable "str" basically holds the correct line being read from the program and, as long as it doesn't equal null, increments the lineCount and then passes the value of the next line to "str," and so on and so on?

Correction; 'str' holds the current line which "was" read from the file. If it's NULL (end of file reached), you break out of the loop, if it isn't, you print out the same and increment the line count.

Edited 6 Years Ago by ~s.o.s~: n/a

This question has already been answered. Start a new discussion instead.