I need to get multiple line Input from a User in Java. Currently I'm using the Scanner class to get the input, but the loop I'm using to check each line does not break.
Current Code
package getxml;
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
System.out.println("Enter the Codes: ");
Scanner in = new Scanner(System.in);
while(in.hasNextLine()) {
String nextLine = in.nextLine();
System.out.println("nextLine:" + nextLine);
}
in.close();
System.out.println("Scanner closed");
}
}
Expected Input
10229892
10120470
10295277
10229618
10229643
10229699
Expected Output
nextLine:10229892
nextLine:10120470
nextLine:10295277
nextLine:10229618
nextLine:10229643
nextLine:10229699
Scanner closed
Real Output
nextLine:10229892
nextLine:10120470
nextLine:10295277
nextLine:10229618
nextLine:10229643
nextLine:10229699
I have tried changing the
hasNextLine()
to
hasNext()
And adding a If condition to break out of the loop with following logic:
if (nextLine.equals("")) {
in.close();
System.out.println("bye");
break;
}
I need to secure the in.nextLine() to a variable, otherwise it will iterate 2 lines in one loop.
