Practical Usage Patterns
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
System.out.print("Enter a double: ");
double decimal = scanner.nextDouble();
}
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter name and age:");
String name = scanner.next();
int age = scanner.nextInt();
}
graph TD
A[Scanner Input Processing] --> B[Single Line Input]
A --> C[Multiple Line Input]
A --> D[Conditional Reading]
A --> E[File Input Processing]
File Reading Techniques
// Reading from a file
try (Scanner fileScanner = new Scanner(new File("data.txt"))) {
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
// Process each line
}
}
Strategy |
Description |
Example |
Type Checking |
Validate input type |
scanner.hasNextInt() |
Range Validation |
Check input boundaries |
value >= 0 && value <= 100 |
Pattern Matching |
Use regex for complex validation |
scanner.hasNext("\\d+") |
Advanced Scanning Techniques
Custom Delimiters
Scanner scanner = new Scanner("apple,banana,cherry");
scanner.useDelimiter(",");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
String input = "Hello World Java Programming";
try (Scanner tokenScanner = new Scanner(input)) {
while (tokenScanner.hasNext()) {
String token = tokenScanner.next();
// Process each token
}
}
Error Handling Patterns
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
try {
System.out.print("Enter a number: ");
if (!scanner.hasNextInt()) {
System.out.println("Invalid input. Try again.");
scanner.next(); // Clear invalid input
continue;
}
int value = scanner.nextInt();
break; // Exit loop on valid input
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
LabEx Learning Approach
LabEx recommends practicing these patterns through interactive coding exercises to master scanner usage in real-world scenarios.