Using scanner.nextLine()
Scanner.nextLine()
is a method of the Scanner
class in Java that reads a line of text from the input. Here's an example of how to use nextLine()
to read a line of text from the console:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a line of text: ");
String line = scanner.nextLine();
System.out.println("You entered: " + line);
}
}
When the program runs, it will print the prompt and wait for the user to enter a line of text. When the user press Enter
, the program will print the line of text they entered.
You can use the nextLine()
method to read other types of data as well, by parsing the input string. For example, to read an integer from the console, you can use the nextInt()
method of the Scanner
class:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
System.out.println("You entered: " + number);
}
}
Note that the Scanner
class is not limited to reading from the console. You can also use it to read from other input sources, like files or strings, by passing a different input source to the Scanner
constructor.