In Java, the Scanner class is used to read input from the user. This input can be anything typed on the keyboard, such as strings, integers, or decimals.
Step 1: Import the Scanner Class
To use the Scanner class, you first need to import it from the java.util package:
import java.util.Scanner;
This line of code allows you to use the Scanner class in your programme.
Creating a Scanner Object
Once you’ve imported the Scanner class, you need to create a Scanner object (which we will refer to as sc in this example):
Scanner sc = new Scanner(System.in);
- Scanner is the class name.
- sc is the variable name (you can choose any name for this variable).
- System.in refers to the standard input stream (the keyboard).
Common Scanner Methods
The Scanner class has many methods to read different types of input. Below are the most commonly used methods:
| Method | Type | What it Reads |
|---|---|---|
next() | String | Reads a single word (stops at space). |
nextLine() | String | Reads an entire line (including spaces). |
nextInt() | int | Reads an integer (whole number). |
nextDouble() | double | Reads a decimal (floating-point number). |
nextBoolean() | boolean | Reads a boolean value (true or false). |
Example: Reading User Input
Here’s a simple Java programme that demonstrates how to read a user’s name and age using the Scanner class:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner sc = new Scanner(System.in);
// Ask for the user's full name
System.out.print("Enter your full name: ");
String name = sc.nextLine(); // Reads the full name
// Ask for the user's age
System.out.print("Enter your age: ");
int age = sc.nextInt(); // Reads the age (integer)
// Display the collected information
System.out.println("Your full name is: " + name);
System.out.println("Your age is: " + age);
// Close the Scanner object to free up resources
sc.close();
}
}
- sc.nextLine(): Reads the whole line of input (name, in this case).
- sc.nextInt(): Reads an integer input (age, in this case). It doesn’t handle decimals or anything other than whole numbers.
- sc.close(): After you’re done using the
Scanner, always callsc.close()to free up system resources.
Summary
- Scanner class in Java is used to read input from the user.
- Import it with
import java.util.Scanner;before use. - Common methods:
next()(word),nextLine()(sentence),nextInt()(integer),nextDouble()(decimal),nextBoolean()(boolean). - Always close the
Scannerobject withsc.close()when done.
Leave a Reply