The Scanner class in Java is versatile and can be used for various input handling tasks. Here are some common uses:
1. Reading Different Data Types:
- String Input:
String text = scanner.nextLine(); - Integer Input:
int number = scanner.nextInt(); - Double Input:
double decimal = scanner.nextDouble();
2. Reading from Files:
You can use Scanner to read data from files:
File file = new File("data.txt");
Scanner fileScanner = new Scanner(file);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
System.out.println(line);
}
fileScanner.close();
3. Tokenizing Input:
Scanner can break input into tokens based on specified delimiters (default is whitespace):
String input = "Java is fun";
Scanner tokenScanner = new Scanner(input);
while (tokenScanner.hasNext()) {
System.out.println(tokenScanner.next());
}
tokenScanner.close();
4. Parsing Input:
You can use Scanner to parse formatted input:
String data = "John 25";
Scanner parseScanner = new Scanner(data);
String name = parseScanner.next();
int age = parseScanner.nextInt();
parseScanner.close();
5. Checking for Valid Input:
You can check if the next input is of a specific type before reading it:
if (scanner.hasNextInt()) {
int value = scanner.nextInt();
} else {
System.out.println("Not an integer!");
}
Summary:
The Scanner class is a powerful tool for handling user input, reading from files, and parsing data in Java applications. If you have more questions or need examples, feel free to ask!
