user1750156
user1750156

Reputation: 35

Java readline( ) while statement, why is this working properly?

I don't understand why this code is working properly, there doesn't appear to be any incrementer or counter that will exit this while loop at some point. What is making the readline function go to the next line in the input file?

            while ((str = in.readLine()) != null) { 
                String [] dat = null;
                dat = baseballstats(str);
                for (int i = 0; i < dat.length; i++) {
                   out.print(dat[i]);
                   out.print (" ");

                }
                out.println();
            } 

I need to make it so that it doesn't print just the first line, but I can't figure out what is making it go to the next line in the input file.

Upvotes: 2

Views: 513

Answers (4)

cmbaxter
cmbaxter

Reputation: 35443

Your loop is a basic while loop in the form:

while(condition){
  ...
}

But in your case, your condition happens to be two parts: an assignment first and then an evaluation. Your condition basically:

  1. Assigns str to the result of in.readLine.
  2. Checks if str is null and if so, exits the loop.

It does this two part condition for every loop iteration until str ends up being null, meaning it's done reading, and the loop exits.

Upvotes: 1

Salih Erikci
Salih Erikci

Reputation: 5087

str changes everytime.It reads the nextline and put it to str.When there is no line remanining str equals to null it exits the loop.

Upvotes: 0

Scott Stanchfield
Scott Stanchfield

Reputation: 30642

readLine() reads all text in the file up to a new-line sequence (\r, \n or \r\n)

If there is no more input, it returns null.

The while loop causes it to keep reading each line until it reaches end of file.

Upvotes: 1

davek
davek

Reputation: 22915

The first line of code does two things: it attempts to read a line of text and then checks if that value is null: if it is, then the reading terminates.

Upvotes: 0

Related Questions