[java] Getting Keyboard Input

How do I get simple keyboard input (an integer) from the user in the console in Java? I accomplished this using the java.io.* stuff, but it says it is deprecated.

How should I do it now?

This question is related to java input console keyboard

The answer is


You can use Scanner to get the next line and do whatever you need to do with the line entered. You can also use JOptionPane to popup a dialog asking for inputs.

Scanner example:

Scanner input = new Scanner(System.in);
System.out.print("Enter something > ");
String inputString = input.nextLine();
System.out.print("You entered : ");
System.out.println(inputString);

JOptionPane example:

String input = JOptionPane.showInputDialog(null,
     "Enter some text:");
JOptionPane.showMessageDialog(null,"You entered "+ input);

You will need these imports:

import java.util.Scanner;
import javax.swing.JOptionPane;

A complete Java class of the above

import java.util.Scanner;
import javax.swing.JOptionPane;
public class GetInputs{
    public static void main(String args[]){
        //Scanner example
        Scanner input = new Scanner(System.in);
        System.out.print("Enter something > ");
        String inputString = input.nextLine();
        System.out.print("You entered : ");
        System.out.println(inputString);

        //JOptionPane example
        String input = JOptionPane.showInputDialog(null,
        "Enter some text:");
        JOptionPane.showMessageDialog(null,"You entered "+ input);
    }
}

import java.util.Scanner; //import the framework


Scanner input = new Scanner(System.in); //opens a scanner, keyboard
System.out.print("Enter a number: "); //prompt the user
int myInt = input.nextInt(); //store the input from the user

Let me know if you have any questions. Fairly self-explanatory. I commented the code so you can read it. :)


Import: import java.util.Scanner;

Define your variables: String name; int age;

Define your scanner: Scanner scan = new Scanner(System.in);

If you want to type:

  • Text: name = scan.nextLine();
  • Integer: age = scan.nextInt();

Close scanner if no longer needed: scan.close();


You can also make it with BufferedReader if you want to validate user input, like this:

import java.io.BufferedReader;
import java.io.InputStreamReader; 
class Areas {
    public static void main(String args[]){
        float PI = 3.1416f;
        int r=0;
        String rad; //We're going to read all user's text into a String and we try to convert it later
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Here you declare your BufferedReader object and instance it.
        System.out.println("Radius?");
        try{
            rad = br.readLine(); //We read from user's input
            r = Integer.parseInt(rad); //We validate if "rad" is an integer (if so we skip catch call and continue on the next line, otherwise, we go to it (catch call))
            System.out.println("Circle area is: " + PI*r*r + " Perimeter: " +PI*2*r); //If all was right, we print this
        }
        catch(Exception e){
            System.out.println("Write an integer number"); //This is what user will see if he/she write other thing that is not an integer
            Areas a = new Areas(); //We call this class again, so user can try it again
           //You can also print exception in case you want to see it as follows:
           // e.printStackTrace();
        }
    }
}

Because Scanner class won't allow you to do it, or not that easy...

And to validate you use "try-catch" calls.


Add line:

import java.util.Scanner;

Then create an object of Scanner class:

Scanner s = new Scanner(System.in);

Now you can call any time:

int a = Integer.parseInt(s.nextLine());

This will store integer value from your keyboard.


If you have Java 6 (You should have, btw) or higher, then simply do this :

 Console console = System.console();
 String str = console.readLine("Please enter the xxxx : ");

Please remember to do :

 import java.io.Console;

Thats it!


You can use Scanner class

Import first :

import java.util.Scanner;

Then you use like this.

Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();

Side note : If you are using nextInt() with nextLine() you probably could have some trouble cause nextInt() does not read the last newline character of input and so nextLine() then is not gonna to be executed with desired behaviour. Read more in how to solve it in this previous question Skipping nextLine using nextInt.


In java we can read input values in 6 ways:

  1. Scanner Class
  2. BufferedReader
  3. Console class
  4. Command line
  5. AWT, String, GUI
  6. System properties
  1. Scanner class: present in java.util.*; package and it has many methods, based your input types you can utilize those methods. a. nextInt() b. nextLong() c. nextFloat() d. nextDouble() e. next() f. nextLine(); etc...
import java.util.Scanner;
public class MyClass {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a :");
        int a = sc.nextInt();
        System.out.println("Enter b :");
        int b = sc.nextInt();
        
        int c = a + b;
        System.out.println("Result: "+c);
    }
}
  1. BufferedReader class: present in java.io.*; package & it has many method, to read the value from the keyboard use "readLine()" : this method reading one line at a time.
import java.io.BufferedReader;
import java.io.*;
public class MyClass {
    public static void main(String args[]) throws IOException {
       BufferedReader br = new BufferedReader(new BufferedReader(new InputStreamReader(System.in)));
        System.out.println("Enter a :");
        int a = Integer.parseInt(br.readLine());
        System.out.println("Enter b :");
        int b = Integer.parseInt(br.readLine());
        
        int c = a + b;
        System.out.println("Result: "+c);
    }
}

You can use Scanner class

To Read from Keyboard (Standard Input) You can use Scanner is a class in java.util package.

Scanner package used for obtaining the input of the primitive types like int, double etc. and strings. It is the easiest way to read input in a Java program, though not very efficient.

  1. To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream (Keyboard).

For example, this code allows a user to read a number from System.in:

Scanner sc = new Scanner(System.in);
     int i = sc.nextInt();

Some Public methods in Scanner class.

  • hasNext() Returns true if this scanner has another token in its input.
  • nextInt() Scans the next token of the input as an int.
  • nextFloat() Scans the next token of the input as a float.
  • nextLine() Advances this scanner past the current line and returns the input that was skipped.
  • nextDouble() Scans the next token of the input as a double.
  • close() Closes this scanner.

For more details of Public methods in Scanner class.

Example:-

import java.util.Scanner;                      //importing class

class ScannerTest {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);       // Scanner object

    System.out.println("Enter your rollno");
    int rollno = sc.nextInt();
    System.out.println("Enter your name");
    String name = sc.next();
    System.out.println("Enter your fee");
    double fee = sc.nextDouble();
    System.out.println("Rollno:" + rollno + " name:" + name + " fee:" + fee);
    sc.close();                              // closing object
  }
}

You can use Scanner class like this:

  import java.util.Scanner;

public class Main{
    public static void main(String args[]){

    Scanner scan= new Scanner(System.in);

    //For string

    String text= scan.nextLine();

    System.out.println(text);

    //for int

    int num= scan.nextInt();

    System.out.println(num);
    }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Examples related to console

Error in MySQL when setting default value for DATE or DATETIME Where can I read the Console output in Visual Studio 2015 Chrome - ERR_CACHE_MISS Swift: print() vs println() vs NSLog() Datatables: Cannot read property 'mData' of undefined How do I write to the console from a Laravel Controller? Cannot read property 'push' of undefined when combining arrays Very simple log4j2 XML configuration file using Console and File appender Console.log not working at all Chrome: console.log, console.debug are not working

Examples related to keyboard

How do I check if a Key is pressed on C++ Move a view up only when the keyboard covers an input field Move textfield when keyboard appears swift Xcode iOS 8 Keyboard types not supported Xcode 6: Keyboard does not show up in simulator How to dismiss keyboard iOS programmatically when pressing return Detect key input in Python Getting Keyboard Input Press Keyboard keys using a batch file Keylistener in Javascript