How to Get Input from a User in Java
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
- 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
May be interested
- What is the difference between Go and Java?is golang better than java? is golang harder than java? can golang replace java? this comparison will give you the answer.
- How to Fix Javajava is a computing platform that allows you to play games and view videos on your computer. you can tell that your computer is having problems with java if you see java errors appear when you try to run a program or visit a website that...
- How to Compile a Java Programthis wikihow teaches you how to turn your java source code into an executable app using a local and online compiler. if you're using a computer, the most common way to compile java code is using java software development kit (java sdk)...
- Oracle wants to turn Java EE into fully open sourcethis week, oracle announced plans to move java ee project management to an open source platform, like apache or eclipse.
- Write and run Java code on the computer for the first timeafter you've installed java and set up a path on your computer, you need to know how to run a simple java code on your computer. in this article, we will try to write the first java program, as well as the commands to run this program in cmd.
- Download Java Runtime Environment 8-build-251java runtime environment (jre) is a software class that provides the services needed to execute java applications. it is an essential component of the java development kit (jdk) and contains all the tools needed to run various java-based software programs.
- How to Enable Javajava is a programming language and platform commonly used in a number of websites and applications. when java is not enabled, you can experience difficulty with viewing or using certain websites and applications. to use java, you must have...
- 200 common Java interview questions, with reference answersif you are going to a java interview, preparing for java programming language questions is necessary. these java interview questions are compiled from tutorialspoint and are accompanied by reference answers.
- What is the difference between Java and JavaScript?although the names of java and javascript seem to be related (javascript seems to be a script in java?), but that's the only similarity. these two languages are not technically related to each other.
- The input () function in Pythonpython's built-in input () function allows users to enter data, convert it into a string, and return the entered content.