User Input in Java
User Input in Java: In Java, user input is typically handled using the Scanner
class, which is part of the java.util
package. This class allows you to read various types of input from different sources like keyboard input, files, and strings. Below is a step-by-step explanation and example of how to use the Scanner
class to read user input from the console.
Steps to Handle User Input in Java
- Import the
Scanner
class: First, you need to import theScanner
class from thejava.util
package. - Create an instance of the
Scanner
class: This instance will be used to read input from the console. - Read input from the user: Use the methods provided by the
Scanner
class to read different types of input (e.g.,nextLine()
,nextInt()
,nextDouble()
, etc.). - Close the
Scanner
: It is good practice to close theScanner
when you are done using it to free up resources.
Example of User Input in Java
Let’s create a simple Java program that reads a user’s name and age from the console.
import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
// Step 2: Create an instance of the Scanner class
Scanner scanner = new Scanner(System.in);
// Step 3: Read input from the user
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Read a line of text
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Read an integer
// Display the user input
System.out.println("Hello, " + name + "! You are " + age + " years old.");
// Step 4: Close the Scanner
scanner.close();
}
}
Explanation
Import the Scanner
class:
import java.util.Scanner;
This statement imports the Scanner
class so you can use it in your program.
Create an instance of the Scanner
class:
Scanner scanner = new Scanner(System.in);
Scanner scanner = new Scanner(System.in);
This creates a Scanner
object that reads input from the standard input stream (System.in
), which is the console.
Read input from the user:
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Reads a line of text
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Reads an integer
nextLine()
: Reads a line of text from the console.nextInt()
: Reads an integer from the console.
Display the user input:
System.out.println("Hello, " + name + "! You are " + age + " years old.");
This line prints the user’s name and age to the console.
Close the Scanner
:
scanner.close();
This closes the Scanner
to free up system resources.
This simple program demonstrates how to read and process user input in Java using the Scanner
class.