Reputation:
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?
Upvotes: 2
Views: 82
Reputation: 152
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.
Upvotes: 1