45

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?

Anthony E
  • 10,363
  • 2
  • 20
  • 42
user1342573
  • 485
  • 1
  • 5
  • 8
  • Be specific. The '`java.io.*` stuff' isn't deprecated. Only `DataInputStream.readLine()`. There is still `BufferedReader.readLine()`, as well as the other suggestions you've been given here. – user207421 May 20 '20 at 10:51

10 Answers10

71

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.

Community
  • 1
  • 1
nachokk
  • 14,055
  • 4
  • 22
  • 47
20

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);
    }
}
Mike B
  • 1,372
  • 1
  • 13
  • 21
15

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.

Frakcool
  • 10,088
  • 9
  • 41
  • 71
  • 1
    I don't understand why you say "Because Scanner class won't allow you to do it, or not that easy..."? IMO you can? – samsamara Aug 09 '16 at 00:34
  • Also if you wanna call that class again (or to continue execution) you should call "a.main(null)" after instantiating, or just do "Areas.main(null)" – samsamara Aug 09 '16 at 00:38
  • @KillBill thanks for your comment, I had forgotten about this question, in a few days I'll try to edit it with a better explanation, when I wrote this answer I was starting my high school studies, today I work in an IT company and I'll write this in the best way I can; back then I was a complete newbie, I can't edit it right now because I have some work to do, but I promise I'll edit and let you know. – Frakcool Aug 09 '16 at 15:48
  • @KillBill Thanks for that method about `Areas.main(null)` but in that case if you want to reuse the code, you should place it inside a method, the code in my answer was made on the main method because I tried to make a [mcve] so anyone who came up my answer could easily copy-paste it and see what it does w/o extra work – Frakcool Aug 09 '16 at 15:50
  • @Frakcool What i wanted to say is your code as is doesn't continue execution. Anyways no worries mate..as your wish – samsamara Aug 10 '16 at 01:40
  • You still need to fix this. `Scanner` can do all this, and without the `try-catch` structure: and if you're going to use `try-catch` you should at least catch the specific `NumberFormatException`, not just `Exception`. – user207421 May 20 '20 at 10:53
10

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
  }
}
anoopknr
  • 2,505
  • 2
  • 14
  • 25
3

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);
    }
}
s-hunter
  • 17,762
  • 11
  • 67
  • 105
3

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();

karlgzafiris
  • 2,695
  • 1
  • 22
  • 28
2
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. :)

Dummy Code
  • 1,758
  • 4
  • 18
  • 38
2

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!

M-D
  • 9,777
  • 9
  • 27
  • 35
1

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.

Pawel
  • 389
  • 4
  • 14
0

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);
    }
}