2

I am accepting multiple lines of info (strings until I parse them later). For example:

1 5 0
2 9 6
2 9 1

I wrote this code to separate the lines because I'm going to have to manipulate each line in a way.

Scanner scan = new Scanner(System.in);
System.out.println("Enter input: ");
ArrayList<String> lines = new ArrayList<String>();


while(scan.hasNextLine()) {
    lines.add(scan.nextLine());
}

System.out.println(lines.get(0));

And I tested this, it does indeed seperate each line of my input and add it into my arraylist, however the part inside the while loop that says scan.nextLine() is checking for more input, causing an infinite loop. How do i fix this?

5
  • When did you expect it to stop? Commented Dec 6, 2017 at 4:12
  • After all of the lines in the multiple-line input have been seperated. Commented Dec 6, 2017 at 4:20
  • There are no lines until you input them. How is the program supposed to know when you're done inputting lines? Commented Dec 6, 2017 at 4:22
  • That's kind of what I'm asking @shmosel, and also I thought that my parameter in the while loop would be good enough in checking if there are anymore lines but apparently not. Commented Dec 6, 2017 at 4:23
  • hasNextLine() isn't capable of reading your mind. You have to decide how to communicate to the program that you don't want it to wait for more input. You might want to go with a predetermined number of lines, or decide on some special input that indicates you're done. Commented Dec 6, 2017 at 4:27

1 Answer 1

1

Scanner is always assumed to have more lines because you can always input more into the console. My suggestion would be to detect for an empty line within your while loop or have a line which has a default character, for example -1, as the first character to let your program know when to end the program. Alternatively, you could use file input which can actually detect if there are more lines.

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.