Scanner provides multiple methods for reading different data types, enabling flexible input processing in Java applications.
Method |
Return Type |
Description |
Example Usage |
nextInt() |
int |
Reads integer input |
int age = scanner.nextInt(); |
nextDouble() |
double |
Reads double input |
double salary = scanner.nextDouble(); |
nextLine() |
String |
Reads entire line |
String name = scanner.nextLine(); |
next() |
String |
Reads next token |
String word = scanner.next(); |
hasNext() |
boolean |
Checks for more input |
while(scanner.hasNext()) { } |
graph TD
A[Scanner Input] --> B{Input Type}
B --> |Primitive| C[Type-Specific Method]
B --> |String| D[Line/Token Method]
B --> |Validation| E[Conditional Checking]
import java.util.Scanner;
public class InputMethodsDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// LabEx Recommended Input Handling
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.print("Enter your salary: ");
double salary = scanner.nextDouble();
System.out.println("Profile: " + name + ", " + age + " years, $" + salary);
scanner.close();
}
}
Error Handling Strategies
Common Exceptions
InputMismatchException
NoSuchElementException
IllegalStateException
Handling Techniques
try {
int value = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid input type");
}
Delimiter-Based Parsing
Scanner fileScanner = new Scanner(new File("data.txt")).useDelimiter(",");
Regular Expression Parsing
Scanner scanner = new Scanner("apple,banana,cherry").useDelimiter(",");
while(scanner.hasNext()) {
System.out.println(scanner.next());
}
Best Practices
- Always match input method with expected data type
- Use
hasNext()
for input validation
- Close scanner after use
- Handle potential exceptions
- Reset scanner if needed