Java How To Ask For User Input - java.util.Scanner
One question that often comes up when learning to code in Java is “How to ask for user input?”. This is pretty easy to do. The methods used are also relatively flexible and allow you to work with multiple different data types.
Quick answer:
import java.util.Scanner;
//...
String data1 = myObj.nextLine(); // take user input
System.out.println("Data read: " + data1); // output user input
Keep reading for a full example with more details. We are also going to show you a few alternate ways of reading user input in Java. We’re going to cover exception handling. We’re also going to cover the Console class and stream readers.
Java User Input Example with Scanner
Here is a somewhat longer, more complete example that also shows how to work with other data types.
NOTE - Inputting the wrong data type can result in an error being thrown. This is something you might want to catch.
import java.util.Scanner;
class Test1 {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter a string: ");
String data1 = myObj.nextLine(); // take user input
System.out.println("Enter an int: ");
int data2 = myObj.nextInt(); // take user input
System.out.println("Enter a double: ");
double data3 = myObj.nextDouble(); // take user input
System.out.println("Data read: " + data1); // Output user input
System.out.println("Data read: " + data2); // Output user input
System.out.println("Data read: " + data3); // Output user input
myObj.close();
}
}
Methods to import different data types using the Scanner class:
next() | Input a String value ( single token ) | |
nextLine() | Input a String value ( line or remainder of current line ) | |
nextBoolean() | Input a boolean value | |
nextByte() | Input a byte value | |
nextDouble() | Input a double value | |
nextFloat() | Input a float value | |
nextInt() | Input a int value from | |
nextLong() | Input a long value | |
We can handle this by | nextShort() | Input a short value |
There are more methods. You can find them in the official documentation HERE and HERE.
Java Scanner - Catching Errors
Entering the wrong data type will cause an exception to be thrown ( ex: String instead of int ). This example will print an error if an InputMismatchException is thrown. We could also put this inside a loop that keeps iterating until valid input has been given.
import java.util.Scanner;
import java.util.InputMismatchException;
class Test1 {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
try {
System.out.println( "Enter an int: " );
int data1 = myObj.nextInt(); // take user input
System.out.println( "Data read: " + data1 ); // Output user input
} catch (InputMismatchException e) {
System.out.println ( "ERROR - Wrong type, enter an int." );
}
myObj.close();
}
}
Java Scanner - Alternative to Catching Errors
This example avoids having to catch exceptions in the first place. It tests if a valid value is present before reading it. It also keeps looping until a valid value is given.
import java.util.Scanner;
class Test1 {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
int data1 = 0;
boolean wrong = false;
do {
System.out.println( "Enter an int: " );
if(myObj.hasNextInt()) {
data1 = myObj.nextInt(); // take user input
wrong = true;
}
else {
myObj.nextLine();
System.out.println ( "Invalid type, enter an int:" );
}
}while(!wrong);
System.out.println( "Data read: " + data1 ); // Output user input
myObj.close();
}
}
How to Take Multiple String Input in Java using Scanner
Multiple strings ( words separated by spaces )
This is pretty easy. Just use the nextLine() method. This will take the entire line or the remainder of the like even if it is separated by spaces.
String data1 = myObj.nextLine(); // take user input
System.out.println("Data read: " + data1); // output user input
Multiple strings ( multiple lines )
If you actually want to read multiple lines as one variable you can change the delimiter like this. In this example it will only stop reading the string when it encounters a “;” even if the user has pressed enter multiple times. This allows for multi line input.
myObj.useDelimiter(";"); // set delmiter
String data1 = myObj.next(); // take user input
System.out.println("Data read: " + data1); // output user input
Java Scanner Read String with Spaces
This is very easy to do. The simplest way to do this is to use nextLine() instead of next().
NOTE - this is basically the same thing that we showed you in the previous section so make sure that you didn’t skip that.
next() | Input a String value ( single token ) |
nextLine() | Input a String value ( line or remainder of current line ) |
If you want a bit more flexibility you can actually specify the delimiter with the next() function.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
Java User Input - Console class
It is also possible to use the Console class to read user input from the command line. Here is an example showing how you might do that.
import java.io.Console;
class Test1 {
public static void main(String[] args) {
Console console = System.console();
System.out.println( "Enter a String: " );
String s = console.readLine();
System.out.println( "Enter an integer: " );
int i = Integer.parseInt(console.readLine());
System.out.println( "Your string: " + s );
System.out.println( "Your number: " + i );
}
}
Java User Input - InputStreamReader and BufferedReader
Another valid option you might want to use when reading user input from the command line would be to use the BufferedReader() and InputStreamReader() classes. Note that we catch an IOException that has been thrown.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class Test1 {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println( "Enter an integer: " );
String s = br.readLine();
int i = Integer.parseInt(s);
System.out.println( "Your number: " + i );
}
catch (IOException e) {
System.out.println (e.toString());
}
}
}
Java User Input - DataInputStream
You can also use the DataInputStream class to read in user data.
You might not want to use this for String input because the readLine() method has been deprecated in the DataInputStream class. This also catches an IOException that was thrown.
NOTE - the readInt() method reads 4 bytes of input. It converts these to an int. This might not be the behavior that you want.
import java.io.DataInputStream;
import java.io.IOException;
class Test1 {
public static void main(String[] args) {
try {
DataInputStream dis = new DataInputStream(System.in);
System.out.println( "Enter an integer: " );
int i = dis.readInt();
System.out.println( "Your number: " + i );
} catch (IOException e) {
System.out.println (e.toString());
}
}
}