How to get the user input in Java?
I attempted to create a calculator, but I can not get it to work because I don't know how to get user input.
How can I get the user input in Java?
Solution 1:
One of the simplest ways is to use a Scanner
object as follows:
import java.util.Scanner;
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
//once finished
reader.close();
Solution 2:
You can use any of the following options based on the requirements.
Scanner
class
import java.util.Scanner;
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();
BufferedReader
and InputStreamReader
classes
import java.io.BufferedReader;
import java.io.InputStreamReader;
//...
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);
DataInputStream
class
import java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();
The readLine
method from the DataInputStream
class has been deprecated. To get String value, you should use the previous solution with BufferedReader
Console
class
import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
Apparently, this method does not work well in some IDEs.