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?
Uh, what’s your question? You just posted some code and said you don’t like pointers. Not understanding pointers can still come back to bite you in java if you don’t understand pass by reference and pass by value.
29 Answers 29
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();
If you close a Scanner object opened to System.in, you will not be able to reopen System.in until the program is finished.
Yeah, ksnortum is right, you get a NoSuchElementException. Somewhat useful related question about why you cannot reopen System.in after closing it.
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.
Note that DataInputStream is for reading binary data. Using readInt on System.in does not parse an integer from the character data, it will instead reinterpret the unicode values and return nonsense. See DataInput#readInt for details ( DataInputStream implements DataInput ).
this is great, would love to see the required imports added for completeness. It would also really help those who need it.
This answer would be a lot more helpful if it mentioned what the requirements actually were. I’ve started a bounty to try to fix this.
For completness sake, you could actually just System.in.read() too since System.in is an InputStream anyways, no need to for any of the wrappers x’] Although that’s definitely frowned upon.
You can use the Scanner class or the Console class
Console console = System.console(); String input = console.readLine("Enter input:");
I believe this will return an error running from almost any IDE. confirmed that intelliJ is having the same issue.
You can get user input using BufferedReader .
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String accStr; System.out.println("Enter your Account number: "); accStr = br.readLine();
It will store a String value in accStr so you have to parse it to an int using Integer.parseInt .
int accInt = Integer.parseInt(accStr);
Here is how you can get the keyboard inputs:
Scanner scanner = new Scanner (System.in); System.out.print("Enter your name"); String name = scanner.next(); // Get what the user types.
The best two options are BufferedReader and Scanner .
The most widely used method is Scanner and I personally prefer it because of its simplicity and easy implementation, as well as its powerful utility to parse text into primitive data.
Advantages of Using Scanner
- Easy to use the Scanner class
- Easy input of numbers (int, short, byte, float, long and double)
- Exceptions are unchecked which is more convenient. It is up to the programmer to be civilized, and specify or catch the exceptions.
- Is able to read lines, white spaces, and regex-delimited tokens
Advantages of BufferedInputStream
- BufferedInputStream is about reading in blocks of data rather than a single byte at a time
- Can read chars, char arrays, and lines
- Throws checked exceptions
- Fast performance
- Synchronized (you cannot share Scanner between threads)
Overall each input method has different purposes.
- If you are inputting large amount of data BufferedReader might be better for you
- If you are inputting lots of numbers Scanner does automatic parsing which is very convenient
For more basic uses I would recommend the Scanner because it is easier to use and easier to write programs with. Here is a quick example of how to create a Scanner . I will provide a comprehensive example below of how to use the Scanner
Scanner scanner = new Scanner (System.in); // create scanner System.out.print("Enter your name"); // prompt user name = scanner.next(); // get user input
(For more info about BufferedReader see How to use a BufferedReader and see Reading lines of Chars)
java.util.Scanner
import java.util.InputMismatchException; // import the exception catching class import java.util.Scanner; // import the scanner class public class RunScanner < // main method which will run your program public static void main(String args[]) < // create your new scanner // Note: since scanner is opened to "System.in" closing it will close "System.in". // Do not close scanner until you no longer want to use it at all. Scanner scanner = new Scanner(System.in); // PROMPT THE USER // Note: when using scanner it is recommended to prompt the user with "System.out.print" or "System.out.println" System.out.println("Please enter a number"); // use "try" to catch invalid inputs try < // get integer with "nextInt()" int n = scanner.nextInt(); System.out.println("Please enter a decimal"); // PROMPT // get decimal with "nextFloat()" float f = scanner.nextFloat(); System.out.println("Please enter a word"); // PROMPT // get single word with "next()" String s = scanner.next(); // ---- Note: Scanner.nextInt() does not consume a nextLine character /n // ---- In order to read a new line we first need to clear the current nextLine by reading it: scanner.nextLine(); // ---- System.out.println("Please enter a line"); // PROMPT // get line with "nextLine()" String l = scanner.nextLine(); // do something with the input System.out.println("The number entered was: " + n); System.out.println("The decimal entered was: " + f); System.out.println("The word entered was: " + s); System.out.println("The line entered was: " + l); >catch (InputMismatchException e) < System.out.println("\tInvalid input entered. Please enter the specified input"); >scanner.close(); // close the scanner so it doesn't leak > >
Note: Other classes such as Console and DataInputStream are also viable alternatives.
Console has some powerful features such as ability to read passwords, however, is not available in all IDE’s (such as Eclipse). The reason this occurs is because Eclipse runs your application as a background process and not as a top-level process with a system console. Here is a link to a useful example on how to implement the Console class.
DataInputStream is primarily used for reading input as a primitive datatype, from an underlying input stream, in a machine-independent way. DataInputStream is usually used for reading binary data. It also provides convenience methods for reading certain data types. For example, it has a method to read a UTF String which can contain any number of lines within them.
However, it is a more complicated class and harder to implement so not recommended for beginners. Here is a link to a useful example how to implement a DataInputStream .
Java: how to read an input int
This is an example of execution I would like to realize:
Integer: eight Input error - Invalid value for an int. Reinsert: 8 secondtoken Input error - Invalid value for an int. Reinsert: 8 8 + 7 = 15
And this is the (incorrect) code I tried to implement:
import java.util.Scanner; import java.util.InputMismatchException; class ReadInt < public static void main(String[] args)< Scanner in = new Scanner(System.in); boolean check; int i = 0; System.out.print("Integer: "); do< check = true; try< i = in.nextInt(); >catch (InputMismatchException e) < System.err.println("Input error - Invalid value for an int."); System.out.print("Reinsert: "); check = false; >> while (!check); System.out.print(i + " + 7 mt24 mb12">javainputjava.util.scanner