Java User Input (Scanner)
The Scanner class in Java is used to get user input, and it is found in java.util package.
To use the Scanner class in Java, we create an object for the class and use any of the methods in the class. In the below example, we use the nextLine() method , which is used to read the Strings:
Example
import java.util.Scanner; //import the Scanner class public class ScannerClass { public static void main (String args[]){ Scanner myObj = new Scanner(System.in); //Create a scanner object System.out.println("Enter best online training institute : "); String institute = myObj.nextLine(); //Read the user input System.out.println("Best online training institute : "+institute); //Print user input } }
Output
Enter best online training institute : SparkDatabox Best online training institute : SparkDatabox
Other Input Types
In the above example, we used nextLine() method to read Strings. To read the other types, we use the below methods:
Method |
Description |
nextBoolean() |
Reads a boolean
value from the user |
nextByte() |
Reads a byte
value from the user |
nextInt() |
Reads a integer
value from the user |
nextFloat() |
Reads a float
value from the user |
nextDouble() |
Reads a double
value from the user |
nextLine() |
Reads a String
value from the user |
nextLong() |
Reads a long
value from the user |
nextShort() |
Reads a short
value from the user |