Scanner Basics
What is Scanner?
Scanner is a fundamental class in Java's java.util package designed for parsing primitive types and strings from input streams. It provides a simple and efficient way to read user input or process data from various sources like files, system input, or string buffers.
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 string
String data = "Hello World";
Scanner stringScanner = new Scanner(data);
// Reading from a file
File file = new File("example.txt");
Scanner fileScanner = new Scanner(file);
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 decimal = scanner.nextDouble(); |
graph LR
A[Input Source] --> B[Scanner]
B --> C{Parse Method}
C -->|next()| D[String Token]
C -->|nextInt()| E[Integer]
C -->|nextDouble()| F[Decimal]
Best Practices
- Always close the scanner after use to prevent resource leaks
- Use appropriate parsing methods based on expected input type
- Handle potential exceptions when reading input
Example Code
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();
}
}
By mastering Scanner basics, you'll be well-equipped to handle various input scenarios in your Java applications. LabEx recommends practicing these techniques to build robust input handling skills.