Joy Kuo
Joy Kuo

Reputation: 31

hasNextLine() while loop not exiting

I understand that I need to use hasNextLine() to advance the line - but when i made a reference to hasNextLine(), I'm not sure why it is still not exiting the while loop:

I'm using a scanner here (sc) to read an input file

while(sc.hasNextLine()){                            
//read post specifications from line
                            String postspecs = sc.nextLine();

                            //split line
                            String[] postspecs_s = postspecs.split(", ");


                            //create post
                            reddit.findUser(stripExtension(argfile.getName())).
                            addPost(postspecs_s[0], PostType.valueOf
                                    (postspecs_s[1]), postspecs_s[2]);

                            System.out.println("created");
                        }

Upvotes: 3

Views: 844

Answers (1)

Jean-François Savard
Jean-François Savard

Reputation: 21004

´hasNextLine´ will only return false if EOF (end of file) char is reached. An easier way to stop reading is to wait for a sentinel value it you are reading from System.in.

So you would have a something like

String s = sc.nextLine();
while(!s.equals(SENTINEL))
    //proceed and dont forget to re-read.

I think ctrl+z will send EOF to system.in on Windows, on iPod atm so can't test.

Upvotes: 1

Related Questions