How to Get Input from a User in Java
When programming in Java or any other language, you will most likely need to use input information from a user. Java provides many different methods for getting in user information, but the most common and perhaps easiest to implement...
Method 1 of 2:
Videos
- Import the Scanner class. You can either choose to import the
java.util.Scanner
class or the entirejava.util
package. To import a class or a package, add one of the following lines to the very beginning of your code:import java.util.Scanner; // This will import just the Scanner class. import java.util.*; // This will import the entire java.util package.
- Initialize a new Scanner object by passing the
System.in
input stream to the constructor.System.in
is the standard input stream that is already open and ready to supply input data. Typically this stream corresponds to keyboard input.Scanner userInputScanner = new Scanner(System.in);
- Read in different kinds of input data that the user enters. The Scanner class supports getting primitives such as int, byte, short, long in addition to getting strings.
- Here are some methods that are available through the Scanner class:
- Read a byte -
nextByte()
- Read a short -
nextShort()
- Read an int -
nextInt()
- Read a long -
nextLong()
- Read a float -
nextFloat()
- Read a double -
nextDouble()
- Read a boolean -
nextBoolean()
- Read a complete line -
nextLine()
- Read a word -
next()
- Read a byte -
- Here is an example of a program that uses different methods of the Scanner class to get different types of input:
import java.util.Scanner; public class ScannerExample { public static void main(String[] args) { // Initiate a new Scanner Scanner userInputScanner = new Scanner(System.in); // Testing nextLine(); System.out.println("nWhat is your name? "); String name = userInputScanner.nextLine(); // Testing nextInt(); System.out.print("How many cats do you have? "); int numberOfCats = userInputScanner.nextInt(); // Testing nextDouble(); System.out.print("How much money is in your wallet? $"); double moneyInWallet = userInputScanner.nextDouble(); System.out.println("nHello " + name + "! You have " + numberOfCats + (numberOfCats > 1 ? " cats" : " cat") + " and $" + moneyInWallet + " in your wallet.n"); } }
- Here are some methods that are available through the Scanner class:
Method 2 of 2:
Handling Exceptions
- Handle input exceptions. An
InputMismatchException
is thrown when the user enters data that doesn't match with the requested type. For example, if the user enters a String when an int is asked for, the program will throw anInputMismatchException
and exit. There are several ways to handle this exception and resolve this problem so that your program can be foolproof. - Use a try-catch block to handle the
InputMismatchException
.import java.util.InputMismatchException; import java.util.Scanner; public class ScannerExample { public static void main(String[] args) { // Initiate a new Scanner Scanner userInputScanner = new Scanner(System.in); // Testing nextLine(); System.out.print("nWhat is your name? "); String name = userInputScanner.nextLine(); // Testing nextInt(); boolean validInput = false; int numberOfCats = 0; while (!validInput) { System.out.print("How many cats do you have? "); try { numberOfCats = userInputScanner.nextInt(); validInput = true; } catch (InputMismatchException e) { validInput = false; userInputScanner.nextLine(); } } // Testing nextDouble(); validInput = false; double moneyInWallet = 0.0; while (!validInput) { System.out.print("How much money is in your wallet? $"); try { moneyInWallet = userInputScanner.nextDouble(); userInputScanner.nextLine(); validInput = true; } catch (InputMismatchException e) { validInput = false; userInputScanner.nextLine(); } } System.out.println("nHello " + name + "! You have " + numberOfCats + (numberOfCats > 1 ? " cats" : "cat") + " and $" + moneyInWallet + " in your wallet.n"); } }
- Note that we have to import
java.util.InputMismatchException
in order to use theInputMismatchException
class. - We are using a while loop to ask the user the same question until the user enters the correct input.
- Adding
userInputScanner.nextLine();
in the catch part of the try-catch ensures that the Scanner acknowledges the "enter" key press from the user and functions as a way to clear the input buffer.
- Note that we have to import
- Alternatively, make the user input foolproof by only taking in next lines from the Scanner. This way, we can ensure that everything that the Scanner returns is a String object and won't create any exceptions. Then, to convert the strings to integers or doubles, we can use the Integer and Double wrapper classes.
import java.util.Scanner; public class ScannerExample { public static void main(String[] args) { // Initiate a new Scanner Scanner userInputScanner = new Scanner(System.in); // Testing nextLine(); System.out.print("nWhat is your name? "); String name = userInputScanner.nextLine(); // Testing nextInt(); boolean validInput = false; int numberOfCats = 0; while (!validInput) { System.out.print("How many cats do you have? "); String input = userInputScanner.nextLine(); try { numberOfCats = Integer.parseInt(input); validInput = true; } catch (NumberFormatException e) { validInput = false; } } // Testing nextDouble(); validInput = false; double moneyInWallet = 0.0; while (!validInput) { System.out.print("How much money is in your wallet? $"); String input = userInputScanner.nextLine(); try { moneyInWallet = Double.parseDouble(input); validInput = true; } catch (NumberFormatException e) { validInput = false; } } System.out.println("nHello " + name + "! You have " + numberOfCats + (numberOfCats > 1 ? " cats" : "cat") + " and $" + moneyInWallet + " in your wallet.n"); } }
- Note that here we did not have to import the
NumberFormatException
class because it is part of the java.lang package, which means that it comes built in. - We also did not have to clear the buffer using
userInputScanner.nextLine();
in the catch part of the try-catch.
- Note that here we did not have to import the
4 ★ | 2 Vote
You should read it
- Some tips with QR Scanner feature on iOS 11
- How to choose a scanner
- 4 best barcode scanning apps for Android
- How to use the built-in virus scanner on Chrome
- How to install Canon Lide 120 scanner
- GitHub's machine learning tool can detect vulnerabilities in code
- How to install and use a vulnerability scanner in Linux
- How to Scan on a Mac
- How to install and use the scanner
- Instructions to scan the network port with Advanced Port Scanner
- 5 ways to use the scanner effectively
- 5 ways hackers 'beat' fingerprint scanner
Maybe you are interested
How to use Microsoft Safety Scanner to scan for malware
The most powerful MRI scanner provides the first accurate images of the human brain
How to Scan barcodes using the Barcode Scanner application on Android phones
How to install and use the scanner
How to choose a scanner
13 portable antivirus and scanner software worth using the most