The Scanner
class in Java provides a convenient way to read user input from the console. It allows developers to prompt the user for various types of data, such as strings, integers, doubles, and more.
Using the Scanner Class
To use the Scanner
class, you first need to import it from the java.util
package:
import java.util.Scanner;
Then, you can create a new Scanner
object that reads input from the system console:
Scanner scanner = new Scanner(System.in);
Once you have a Scanner
object, you can use its various methods to prompt the user for input and read the data. Here are some common examples:
Reading a String
System.out.print("Please enter your name: ");
String name = scanner.nextLine();
Reading an Integer
System.out.print("Please enter your age: ");
int age = scanner.nextInt();
Reading a Double
System.out.print("Please enter your height (in meters): ");
double height = scanner.nextDouble();
When prompting for user input, it's important to validate the input to ensure that it's in the expected format. The Scanner
class provides several methods to help with this, such as hasNextInt()
, hasNextDouble()
, and hasNextLine()
.
while (!scanner.hasNextInt()) {
System.out.print("Invalid input. Please enter an integer: ");
scanner.nextLine(); // Consume the invalid input
}
int number = scanner.nextInt();
By using the Scanner
class and following best practices for input validation, you can create robust and user-friendly console applications in Java.