Scanner provides versatile methods for processing different types of input efficiently. Understanding these methods is crucial for effective data handling.
Method |
Description |
Return Type |
next() |
Reads next token |
String |
nextLine() |
Reads entire line |
String |
nextInt() |
Reads integer |
int |
nextDouble() |
Reads double |
double |
nextBoolean() |
Reads boolean |
boolean |
graph TD
A[Input Source] --> B{Validate Input}
B --> |Valid| C[Process Input]
B --> |Invalid| D[Handle Exception]
C --> E[Store/Use Data]
import java.util.Scanner;
public class MultiInputProcessing {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name: ");
String name = scanner.nextLine();
System.out.print("Enter age: ");
int age = scanner.nextInt();
System.out.print("Enter salary: ");
double salary = scanner.nextDouble();
System.out.println("Profile: " + name + ", Age: " + age + ", Salary: " + salary);
scanner.close();
}
}
Delimiter Customization
Scanner scanner = new Scanner("apple,banana,cherry");
scanner.useDelimiter(",");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()) {
System.out.println("Invalid input. Please enter an integer.");
scanner.next(); // Consume invalid input
}
int validNumber = scanner.nextInt();
- Close Scanner after use
- Choose appropriate reading method
- Handle potential input mismatches
- Use try-catch for robust error handling
At LabEx, we emphasize practical approaches to mastering input processing techniques in Java.