简体   繁体   中英

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");
                        }

´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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM