Scanning multiple lines using single scanner object
By default, the scanner uses space as a delimiter. In order to scan by lines using forEachRemaining, change the scanner delimiter to line as below.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\n");
scanner.forEachRemaining(System.out::println);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("Please specify how many lines you want to enter: ");
String[] input = new String[in.nextInt()];
in.nextLine(); //consuming the <enter> from input above
for (int i = 0; i < input.length; i++) {
input[i] = in.nextLine();
}
System.out.printf("\nYour input:\n");
for (String s : input) {
System.out.println(s);
}
}
Sample execution:
Please specify how many lines you want to enter: 3
Line1
Line2
Line3
Your input:
Line1
Line2
Line3
public class Sol{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}