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?
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?
Add line:
Then create an object of
Scanner
class:Now you can call any time:
This will store
integer
value from your keyboard.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:
name = scan.nextLine();
age = scan.nextInt();
Close scanner if no longer needed:
scan.close();
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 likeint, double
etc. andstrings
. It is the easiest way to read input in a Java program, though not very efficient.object
ofScanner
class, we usually pass the predefined objectSystem.in
, which represents the standard input stream (Keyboard).For example, this code allows a user to read a number from System.in:
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.
Exaple:-