3

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");
                        }
6
  • What is it doing instead? Commented Feb 16, 2015 at 1:46
  • it is reading a txt file line to line and storing elements of that file into an array of string. then i use the elements of the array of string to create an object as seen in the last couple of lines. in the end i print created (just so i know how many times it went through the while loop) Commented Feb 16, 2015 at 2:23
  • I know what it's supposed to do. Since you said it doesn't work, I assume it doesn't do that. What does it do? Commented Feb 16, 2015 at 2:25
  • its not exiting the while loop - which means it continues to print created endlessly. Commented Feb 16, 2015 at 2:27
  • if you print out postspecs what does it print? Commented Feb 16, 2015 at 2:29

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.