In Java, user input can be obtained through the use of the Scanner
class, which is part of the java.util
package. The Scanner
class provides a convenient way to read user input from the console or from a file.
To use the Scanner
class to read user input from the console, you first need to create a new instance of the class and pass the System.in
object to its constructor. For example:
import java.util.Scanner; public class UserInputExample { 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("Hello, " + name + ". You are " + age + " years old."); } }
In the above example, we create a new Scanner
object called scanner
and pass System.in
to its constructor. We then use the nextLine()
method to read a line of text from the console, and the nextInt()
method to read an integer value. Finally, we use the values we obtained to print a message to the console.
The Scanner
class provides many other useful methods for reading different types of data, such as nextBoolean()
, nextDouble()
, and nextLong()
. It also provides methods for reading from files and other input sources.
It’s important to note that when using the Scanner
class to read user input, you should always validate the input to ensure that it is of the expected type and format, and handle any exceptions that may occur.