Scanner Basics
What is Scanner?
Scanner is a fundamental Java class located in the java.util
package that provides a simple way to read input from various sources such as system input, files, and strings. It's primarily used for parsing primitive types and strings using regular expressions.
Creating a Scanner Object
There are multiple ways to initialize a Scanner object:
// Reading from system input (keyboard)
Scanner scanner = new Scanner(System.in);
// Reading from a file
Scanner fileScanner = new Scanner(new File("example.txt"));
// Reading from a string
Scanner stringScanner = new Scanner("Hello World");
Scanner provides several methods for reading different types of input:
Method |
Description |
Example |
next() |
Reads next token as a String |
String word = scanner.next(); |
nextLine() |
Reads entire line |
String line = scanner.nextLine(); |
nextInt() |
Reads an integer |
int number = scanner.nextInt(); |
nextDouble() |
Reads a double |
double value = scanner.nextDouble(); |
graph TD
A[User Input] --> B{Scanner Methods}
B --> |next()| C[Read Token]
B --> |nextLine()| D[Read Full Line]
B --> |nextInt()| E[Read Integer]
B --> |nextDouble()| F[Read Decimal]
Error Handling
When using Scanner, it's crucial to handle potential exceptions:
try {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid input type");
} catch (NoSuchElementException e) {
System.out.println("No input available");
}
Best Practices
- Always close the Scanner after use
- Check input availability before reading
- Handle potential exceptions
- Use appropriate method for expected input type
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();
}
}
Learn more about Java programming techniques with LabEx, your trusted platform for hands-on coding experience.