instagram

Getting User Input using Java

In order to get an input from the user, there is a special class used called as Scanner.
The Scanner class is defined by java. Whenever you want to use a scanner class, you have to import it as import java.util.Scanner; which is shown in the example below.

Example
package ABC;

import java.util.Scanner;
public class MyClass{
         public static void main(String[] args){
                  Scanner scan = new Scanner(system.in);
                  System.out.println("Enter some number");
                  int user_input_num = scan.nextInt();
                  System.out.println("The entered value is");
                  System.out.print(user_input_num);
          }
}

As shown in the above code, we have created an object scan, since we are using an integer value, we have to use scan.nextInt();
There is a variable defined as user_input_num which is then printed.

Similarly, the user can print the values such as float, boolean, double, string etc.
For example, to print the double value you can write nextDouble();
To print the string value, you can write nextLine();

Now, after running the above code you will get the following output:

Enter some number
1000
The entered value is
1000

Share