In Java, there are several ways to get user input, and the most common method is using the Scanner
class. The Scanner
class is part of the java.util
package and provides a simple way to read input from the console, files, or other sources.
Using the Scanner Class
To get user input using the Scanner
class, you need to follow these steps:
- Import the
java.util.Scanner
class at the beginning of your Java program.
- Create a new
Scanner
object and associate it with the desired input source (e.g., the console).
- Use the appropriate
Scanner
method to read the user's input.
Here's an example of how to use the Scanner
class to get user input:
import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
// Create a new Scanner object to read input from the console
Scanner scanner = new Scanner(System.in);
// Prompt the user for input
System.out.print("Enter your name: ");
// Read the user's input and store it in a variable
String name = scanner.nextLine();
// Print the user's input
System.out.println("Hello, " + name + "!");
}
}
In this example, we create a Scanner
object and associate it with the console (System.in
). We then use the nextLine()
method to read the user's input as a String
. Finally, we print a greeting that includes the user's input.
Reading Different Data Types
The Scanner
class provides methods to read different data types, such as nextInt()
for integers, nextDouble()
for floating-point numbers, and nextBoolean()
for boolean values. Here's an example of how to read different data types:
import java.util.Scanner;
public class MultipleInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt the user for input
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.print("Enter your height (in meters): ");
double height = scanner.nextDouble();
System.out.print("Are you a student? (true/false): ");
boolean isStudent = scanner.nextBoolean();
// Print the user's input
System.out.println("You are " + age + " years old.");
System.out.println("Your height is " + height + " meters.");
System.out.println("Is student? " + isStudent);
}
}
In this example, we use the nextInt()
, nextDouble()
, and nextBoolean()
methods to read different data types from the user.
Remember to always close the Scanner
object when you're done using it to prevent resource leaks.