Scanner Class Methods
Overview of Scanner Class
The Scanner
class in Java provides a powerful and flexible way to parse console input, supporting various data types and input parsing techniques.
Key Scanner Methods
Method |
Return Type |
Description |
next() |
String |
Reads next token as a String |
nextLine() |
String |
Reads entire line of input |
nextInt() |
int |
Reads an integer value |
nextDouble() |
double |
Reads a double value |
hasNext() |
boolean |
Checks if more input exists |
Basic Scanner Usage
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Hello, " + name + "! You are " + age + " years old.");
scanner.close();
}
}
graph TD
A[Create Scanner Object] --> B[Prompt for Input]
B --> C[Read Input Using Scanner Methods]
C --> D[Process Input]
D --> E[Close Scanner]
Advanced Scanner Techniques
Delimiter Configuration
Scanner scanner = new Scanner(System.in).useDelimiter("\n");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name, age, and salary: ");
String name = scanner.next();
int age = scanner.nextInt();
double salary = scanner.nextDouble();
Common Pitfalls
- Not closing the scanner
- Mixing
next()
and nextLine()
methods
- Handling input type mismatches
LabEx Tip
At LabEx, we recommend practicing different Scanner methods to become proficient in console input handling.
Error Handling
import java.util.Scanner;
import java.util.InputMismatchException;
public class SafeScannerDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
System.out.println("You entered: " + number);
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter an integer.");
} finally {
scanner.close();
}
}
}
Conclusion
The Scanner
class offers a robust and user-friendly approach to reading console input in Java, supporting multiple data types and input parsing strategies.