Getting User Input in Java: The Scanner Class
Welcome! In this video, we'll dive into the process of acquiring user input in the Java programming language using the Scanner class. The Scanner class is a powerful tool that allows us to capture data input from the console, making our programs interactive and user-friendly.
What is the Scanner Class?
The Scanner class resides within the java.util package. It offers various methods to read text input from different sources, such as console input and files. The Scanner divides the input into tokens, which are pieces of text separated by whitespace (spaces and tabs) or any other specified delimiter.
How to Use the Scanner Class
To utilize the Scanner class, follow these steps:
Import the necessary package: Begin by importing the java.util package into your program. You can achieve this using the following statement:
Java
import java.util.Scanner;
Use code with caution.
content_copy
Create a Scanner object: Now, create an object of the Scanner class. This object specifies the source from which you want to read the input. Typically, we use System.in for console input:
Java
Scanner scanner = new Scanner(System.in);
Use code with caution.
content_copy
Get Input: The Scanner object provides various methods to read different data types entered by the user. Here are some of these methods:
nextInt(): Reads integer input.
nextDouble(): Reads double (floating-point number) input.
nextLine(): Reads an entire line of text as a string.
next(): Reads the next token as a string.
For example, the following code reads an integer representing the user's age:
Java
int age = scanner.nextInt();
Use code with caution.
content_copy
Process the Input: Once you've obtained the input, you can use it within your program logic. For instance, you could use the retrieved age to determine a person's eligibility to vote.
Close the Scanner object: Finally, it's good practice to close the Scanner object when you're finished using it to release resources. You can achieve this using the close() method:
Java
scanner.close();
Use code with caution.
content_copy
Example:
The following example demonstrates how to acquire a user's name and age using the Scanner class:
Java
import java.util.Scanner;
public class Main {
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("Your name is " + name + " and you are " + age + " years old.");
scanner.close();
}
}
Use code with caution.
content_copy
This code prompts the user for their name and age, reads the input using nextLine() and nextInt(), and then displays a message combining the entered information.