Introduction
The Scanner
class in Java, part of the java.util
package, is a utility class used to parse primitive types and strings using regular expressions.
It can read input from various sources, including strings, files, and input streams.
The Scanner
class is widely used for reading user input in console applications.
Table of Contents
- What is the
Scanner
Class? - Common Methods
- Examples of Using the
Scanner
Class - Conclusion
1. What is the Scanner Class?
The Scanner
class provides methods for reading and parsing primitive types (like int
, double
, etc.) and strings from different sources such as the console, files, and other input streams. It uses delimiters (default is whitespace) to separate the tokens in the input.
2. Common Methods
next()
: Finds and returns the next complete token from this scanner.nextLine()
: Advances the scanner past the current line and returns the input that was skipped.nextInt()
: Scans the next token of the input as anint
.nextDouble()
: Scans the next token of the input as adouble
.hasNext()
: Returnstrue
if this scanner has another token in its input.hasNextInt()
: Returnstrue
if the next token in this scanner's input can be interpreted as anint
value.hasNextDouble()
: Returnstrue
if the next token in this scanner's input can be interpreted as adouble
value.close()
: Closes the scanner.useDelimiter(String pattern)
: Sets this scanner's delimiting pattern.
3. Examples of Using the Scanner Class
Example 1: Reading User Input from the Console
This example demonstrates how to read different types of user input from the console.
import java.util.Scanner;
public class ScannerConsoleExample {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("You are " + age + " years old.");
System.out.print("Enter your height (in meters): ");
double height = scanner.nextDouble();
System.out.println("Your height is " + height + " meters.");
}
}
}
Output:
Enter your name: Rajesh
Hello, Rajesh!
Enter your age: 28
You are 28 years old.
Enter your height (in meters): 1.75
Your height is 1.75 meters.
Example 2: Reading from a File
This example shows how to use the Scanner
class to read data from a file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerFileExample {
public static void main(String[] args) {
File file = new File("example.txt");
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("File not found.");
e.printStackTrace();
}
}
}
Output (assuming example.txt
contains the following content):
This is the first line.
This is the second line.
This is the third line.
Example 3: Using Different Delimiters
This example demonstrates how to use different delimiters with the Scanner
class.
import java.util.Scanner;
public class ScannerDelimiterExample {
public static void main(String[] args) {
String input = "apple,orange,banana";
try (Scanner scanner = new Scanner(input)) {
scanner.useDelimiter(",");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
}
}
}
Output:
apple
orange
banana
Example 4: Reading Multiple Data Types
This example shows how to read different data types from a single input string.
import java.util.Scanner;
public class ScannerMultipleTypesExample {
public static void main(String[] args) {
String input = "Anjali 25 5.4 true";
try (Scanner scanner = new Scanner(input)) {
String name = scanner.next();
int age = scanner.nextInt();
double height = scanner.nextDouble();
boolean isStudent = scanner.nextBoolean();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Is Student: " + isStudent);
}
}
}
Output:
Name: Anjali
Age: 25
Height: 5.4
Is Student: true
Example 5: Handling Exceptions
This example demonstrates how to handle exceptions when using the Scanner
class.
import java.util.InputMismatchException;
import java.util.Scanner;
public class ScannerExceptionExample {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
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.");
}
}
}
Output (when entering a non-integer value):
Enter an integer: hello
Invalid input. Please enter an integer.
4. Conclusion
The Scanner
class in Java provides a convenient way to read and parse various types of input from different sources. By using the methods provided by the Scanner
class, developers can easily handle user input, read from files, and process strings with custom delimiters.
Using the try-with-resources statement ensures that the scanner is closed properly, following best practices for resource management.
Comments
Post a Comment
Leave Comment