Explanation regarding skipping of alternate lines while reading from a file?

I just want to know, have I interpreted the code in right manner?

The file Bharath.txt has the following content:

Hello ! B . We created your file succesfully . We have updated you file , Sir ! Bharath Nikhil Friends Indeed

Consider the below code:

import java.util.Scanner;
import java.io.*;

class FilInpStr
{
    public static void main(String arg[]) throws Exception
    {
        FileInputStream obj=new FileInputStream("Bharath.txt");
        Scanner input=new Scanner(obj);

        String n="";
        while((n=input.nextLine())!=null)
        {
            System.out.println(n);
        }

    }
}

The above code works well this way. But when I do not consider storing input.nextLine() in a String, it begins to skip line alternatively. Is it that it is taking even the Enter from keyboard as input?

So, when I press Enter, it is passing the escape sequence too, as an input, which is why it is skipping one and printing the other?

And another doubt was regarding the while loop: is that one line wasted while comparing whether it is null or not?

  1. Bharath
  2. Nikhil
  3. Friends Indeed

So, when I quote:

while((input.nextLine()) != null)
{
    System.out.println(input.nextLine());
}

It will check whether Bharath==null or not, and if not, it will only then print Nikhil? And post Nikhil, it will skip next line, because it takes Enter as an escape sequence.

Please, correct me! I might have mixed up two different approaches. A beginner hence.

Also, do mention in distinction the difference between passing the input.nextLine() into a String, and as standalone code.

Jon Skeet
people
quotationmark

But , when I do not consider storing " input.nextLine()" in a String , it begins to skip line alternatively . Is it , that , it is taking even the ENTER from keyboard as input ?

Well no, it's just reading the next line every time you call input.nextLine(). That shouldn't be surprising. Ignore escape sequences etc. For the sake of simplicity, assume that input.nextLine() is just reading from a list of strings somewhere... it has a cursor showing where on the list it is. Every time you call input.nextLine(), it returns the current line and moves the cursor down.

If you call input.nextLine() twice in each iteration (once in the while condition and once inside the body) then you'll only execute half as many iterations as if you call it once per iteration (as per your original code).

people

See more on this question at Stackoverflow