Scanner Basics
What is Scanner?
Scanner is a built-in Java class that provides a simple way to read input from various sources such as the console, files, or strings. It is part of the java.util
package and offers an easy-to-use mechanism for parsing primitive types and strings.
Creating a Scanner Object
To use Scanner, you first need to import the class and create an instance. Here are the most common ways to initialize a Scanner:
// Reading from standard input (keyboard)
Scanner scanner = new Scanner(System.in);
// Reading from a string
String input = "Hello World";
Scanner stringScanner = new Scanner(input);
// Reading from a file
File file = new File("example.txt");
Scanner fileScanner = new Scanner(file);
Scanner provides several methods to read different types of input:
Method |
Description |
Example |
next() |
Reads the next token as a String |
String word = scanner.next(); |
nextLine() |
Reads an entire line of text |
String line = scanner.nextLine(); |
nextInt() |
Reads the next integer |
int number = scanner.nextInt(); |
nextDouble() |
Reads the next double |
double value = scanner.nextDouble(); |
graph TD
A[User Input] --> B{Scanner}
B --> |next()| C[Token]
B --> |nextLine()| D[Full Line]
B --> |nextInt()| E[Integer]
B --> |nextDouble()| F[Decimal Number]
Best Practices
- Always close the Scanner when you're done using it
- Use appropriate input method based on expected input type
- Handle potential
InputMismatchException
// Example of proper Scanner usage
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Hello, " + name + "! You are " + age + " years old.");
}
At LabEx, we recommend practicing with Scanner to improve your Java input handling skills.