0% completed
In Java, user input is commonly handled using the Scanner class. This class, part of the java.util
package, provides methods to read various types of data such as integers, floating-point numbers, strings, and booleans from the user.
The Scanner class allows programs to read input from a variety of sources, including the keyboard. It is part of Java's standard library, so you only need to import it at the beginning of your program:
import java.util.Scanner;
To use the Scanner, you first create an object of the Scanner class. Below is the syntax:
Scanner scanner = new Scanner(System.in);
Scanner
: The class name to create a Scanner object.scanner
: The name of the Scanner object (can be any valid variable name).System.in
: Refers to the standard input stream, which is the keyboard.The Scanner class provides specific methods to read input depending on the data type. Here are some common methods:
Method | Description | Example Input |
---|---|---|
nextInt() | Reads an integer | 10 |
nextDouble() | Reads a floating-point number | 3.14 |
next() | Reads a single word (until a space) | Hello |
nextLine() | Reads an entire line of text | Hello World |
nextBoolean() | Reads a boolean value (true /false ) | true |
This example demonstrates how to use the Scanner class to read an integer input from the user.
Explanation:
Scanner scanner = new Scanner(System.in);
: Creates a Scanner object named scanner
to read input from the keyboard (System.in
).System.out.print("Enter an integer: ");
: Displays a message prompting the user to enter an integer. The print()
method is used to keep the cursor on the same line.int number = scanner.nextInt();
: Reads the integer input from the user and stores it in the variable number
.System.out.println("You entered: " + number);
: Prints the value of number
to confirm the input.scanner.close();
: Closes the Scanner object to release system resources.In this example, we use the Scanner class to read a string (name) and a double (favorite number).
Explanation:
Scanner scanner = new Scanner(System.in);
: Creates a Scanner object to read input.System.out.print("Enter your name: ");
: Displays a prompt asking the user for their name.String name = scanner.nextLine();
: Reads a full line of input (including spaces) entered by the user and stores it in the name
variable.System.out.print("Enter your favorite number: ");
: Prompts the user to input a number.double favoriteNumber = scanner.nextDouble();
: Reads a double (floating-point number) input and stores it in favoriteNumber
.System.out.println(...)
: Combines the name
and favoriteNumber
variables into a message and prints it.scanner.close();
: Closes the Scanner to release resources.The Scanner class makes it easy to create interactive Java programs by reading user input. Experiment with the examples provided and try reading different types of input to become familiar with its methods.
.....
.....
.....