Scanner Basics
What is Scanner?
Scanner is a built-in Java class located in the java.util
package that provides a simple way to read input from various sources, such as the console, files, or strings. It's primarily used for parsing primitive types and strings using regular expressions.
Creating a Scanner Object
To use Scanner, you need to import it and create an instance. There are multiple ways to initialize a Scanner:
import java.util.Scanner;
// Reading from System.in (console input)
Scanner scanner = new Scanner(System.in);
// Reading from a file
Scanner fileScanner = new Scanner(new File("example.txt"));
// Reading from a string
Scanner stringScanner = new Scanner("Hello World");
Scanner provides various methods to read different types of input:
Method |
Description |
Return Type |
next() |
Reads the next token |
String |
nextLine() |
Reads an entire line |
String |
nextInt() |
Reads an integer |
int |
nextDouble() |
Reads a double |
double |
hasNext() |
Checks if there's another token |
boolean |
graph TD
A[Start] --> B[Create Scanner]
B --> C{Input Method}
C --> |nextInt()| D[Read Integer]
C --> |nextLine()| E[Read Line]
C --> |next()| F[Read Token]
D --> G[Process Input]
E --> G
F --> G
G --> H[Close Scanner]
Error Handling
When using Scanner, it's important to handle potential exceptions:
Scanner scanner = new Scanner(System.in);
try {
int number = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid input type");
} finally {
scanner.close();
}
Best Practices
- Always close the Scanner when you're done
- Use appropriate input methods
- Handle potential input exceptions
- Consider input validation
LabEx Tip
When learning Java input techniques, LabEx provides interactive coding environments that can help you practice and master Scanner usage effectively.