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++;
}

A good example of the difference between calling a function and reading a variable.

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?

correct* should be current :P

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.