To scan multiple lines in one step with a single `Scanner` object in Java, use the following code:
import java.util.Scanner;
public class MultiLineScanner {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read the first integer
int number = scanner.nextInt();
scanner.nextLine(); // Consume the newline
// Read subsequent lines
String line1 = scanner.nextLine();
String line2 = scanner.nextLine();
String line3 = scanner.nextLine();
// Close the scanner
scanner.close();
}
}
This code allows you to enter:
5
hello how do you do
Welcome to my world
6 7
and reads them into variables using a single Scanner instance.