Advanced Scanner Techniques
Custom Delimiter Techniques
Configuring Delimiters
import java.util.Scanner;
public class CustomDelimiterDemo {
public static void main(String[] args) {
// Using custom delimiter
String input = "apple,banana;orange:grape";
Scanner scanner = new Scanner(input).useDelimiter("[,;:]");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
}
}
Delimiter Types
Delimiter Type |
Use Case |
Example |
Comma |
CSV parsing |
"1,2,3,4" |
Whitespace |
Token separation |
"hello world" |
Regex |
Complex parsing |
"[,;:]" |
public class AdvancedParsingDemo {
public static void parseComplexInput(String input) {
Scanner scanner = new Scanner(input);
scanner.useDelimiter("\\s*,\\s*");
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
System.out.println("Integer: " + scanner.nextInt());
} else {
System.out.println("String: " + scanner.next());
}
}
scanner.close();
}
}
Scanner Parsing Workflow
graph TD
A[Input String] --> B[Configure Scanner]
B --> C{Parse Tokens}
C -->|Integer| D[Process Integer]
C -->|String| E[Process String]
D, E --> F{More Tokens?}
F -->|Yes| C
F -->|No| G[Close Scanner]
File Reading Techniques
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileReadingDemo {
public static void readFileWithScanner(String filepath) {
try (Scanner scanner = new Scanner(new File(filepath))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
processLine(line);
}
} catch (FileNotFoundException e) {
System.err.println("File not found: " + filepath);
}
}
private static void processLine(String line) {
// Custom line processing logic
System.out.println(line);
}
}
Optimization Technique |
Description |
Try-with-resources |
Automatic resource management |
Buffered Reading |
Efficient for large files |
Selective Parsing |
Process only required tokens |
public class InputValidator {
public static boolean validateInput(Scanner scanner,
InputType type) {
switch(type) {
case INTEGER:
return scanner.hasNextInt();
case DOUBLE:
return scanner.hasNextDouble();
case EMAIL:
return validateEmail(scanner.next());
default:
return false;
}
}
private static boolean validateEmail(String email) {
// Complex email validation logic
return email.contains("@");
}
}
graph LR
A[Scanner Input] --> B{Parsing Strategy}
B -->|Efficient| C[Optimized Processing]
B -->|Inefficient| D[Performance Overhead]
Best Practices for LabEx Learners
- Use appropriate delimiters
- Implement robust error handling
- Close scanner resources
- Choose efficient parsing strategies
- Validate input before processing
Conclusion
Advanced Scanner techniques require a deep understanding of input parsing, delimiter configuration, and performance optimization. By mastering these techniques, developers can create more robust and efficient Java applications.