Getting Keyboard Input

user1342573 picture user1342573 · Jul 9, 2013 · Viewed 509.5k times · Source

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?

Answer

nachokk picture nachokk · Jul 9, 2013

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.