The Scanner class, found in the java.util package, facilitates obtaining user input in Java.
Utilize the Scanner class by instantiating an object of the class and employing any of its methods as detailed in the Scanner class documentation. For instance, in our example, we will utilize the nextLine() method, designed for reading Strings.
import
|
If you are unfamiliar with what a package is, please refer to our Java Packages Tutorial. |
In the aforementioned example, we utilized the nextLine() method specifically tailored for reading Strings. For reading other data types, refer to the table provided below.
Method |
Description |
|
Obtains a boolean value from the user. |
|
Obtains a byte value from the user. |
|
Obtains a double value from the user. |
|
Obtains a float value from the user. |
|
Obtains an int value from the user |
|
Obtains a String value from the user. |
|
Obtains a long value from the user. |
|
Obtains a short value from the user. |
In the following example, we employ various methods to read data of different types:
import
|
Note: Providing incorrect input, such as text in a numerical input field, will result in an exception or error message, such as “InputMismatchException.” For further information on exceptions and error handling, you can explore the Exceptions chapter. |