Java User Input
Java User Input
Java User Input
To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation. In our example,
we will use the nextLine() method, which is used to read Strings:
Example
import java.util.Scanner; // Import the Scanner class
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner
object
System.out.println("Enter username");
If you don't know what a package is, read our Java Packages Tutorial.
Input Types
In the example above, we used the nextLine() method, which is used to read
Strings. To read other types, look at the table below:
Method Description
nextBoolean() Reads a boolean value from the user
In the example below, we use different methods to read data of various types:
Example
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();