Java (programming language)
Java Scanner Class | Java Scanner Demo Program
Introduction
- Purpose: The Scanner class in Java streamlines the process of obtaining user input. It parses various data types from a variety of input sources, including the keyboard, files, and strings.
- Key Features:
- Tokenizes input using delimiters (e.g., whitespace by default).
- Offers methods to read various data types, including int, double, String, boolean, and more.
- Compatible with diverse input sources, enhancing flexibility.
Creating a Scanner Object
- Import the Scanner class:
Java
import java.util.Scanner;
- Construct a Scanner object:
Java
Scanner scanner = new Scanner(System.in); // Reads from standard input (keyboard)
Scanner fileScanner = new Scanner(new File("myFile.txt")); // Reads from a file
Scanner stringScanner = new Scanner("This is a string"); // Reads from a string
Reading Different Data Types
- Read an integer:
Java
int age = scanner.nextInt();
- Read a double:
Java
double price = scanner.nextDouble();
- Read a String:
Java
String name = scanner.nextLine();
- Read a boolean:
Java
boolean isTrue = scanner.nextBoolean();
- Read a single character:
Java
char initial = scanner.next().charAt(0);
Important Considerations
- Whitespace and nextLine():
nextInt()
,nextDouble()
, and similar methods consume input only up to the first whitespace character. To read an entire line, including spaces, usenextLine()
. - Closing Scanners: To release resources, consider closing Scanner objects after use:
Java
scanner.close();
Demo Program
Java
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();
}
}
Additional Features
- Changing the delimiter: Use
useDelimiter()
to set a custom delimiter. - Checking for the next token: Use
hasNext()
methods to verify the presence of the next token of a specific type (e.g.,hasNextInt()
,hasNextLine()
). - Reading tokens as specific data types: Use methods like
nextInt()
,nextDouble()
,nextBoolean()
, andnext()
to read tokens as specific data types.
Conclusion
The Scanner class empowers Java developers to efficiently gather user input and parse data from various sources. Its versatility and ease of use make it an invaluable tool for interactive programs and data processing tasks.