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

  1. How to Get Input from a User in Java Picture 1How to Get Input from a User in Java Picture 1
    Import the Scanner class. You can either choose to import the java.util.Scanner class or the entire java.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. 
  2. How to Get Input from a User in Java Picture 2How to Get Input from a User in Java Picture 2
    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); 
  3. How to Get Input from a User in Java Picture 3How to Get Input from a User in Java Picture 3
    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.
    1. Here are some methods that are available through the Scanner class:
      1. Read a byte - nextByte()
      2. Read a short - nextShort()
      3. Read an int - nextInt()
      4. Read a long - nextLong()
      5. Read a float - nextFloat()
      6. Read a double - nextDouble()
      7. Read a boolean - nextBoolean()
      8. Read a complete line - nextLine()
      9. Read a word - next()
    2. 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"); } } 
Method 2 of 2:

Handling Exceptions

  1. How to Get Input from a User in Java Picture 4How to Get Input from a User in Java Picture 4
    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 an InputMismatchException and exit. There are several ways to handle this exception and resolve this problem so that your program can be foolproof.
  2. How to Get Input from a User in Java Picture 5How to Get Input from a User in Java Picture 5
    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"); } } 
    1. Note that we have to import java.util.InputMismatchException in order to use the InputMismatchException class.
    2. We are using a while loop to ask the user the same question until the user enters the correct input.
    3. 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.
  3. How to Get Input from a User in Java Picture 6How to Get Input from a User in Java Picture 6
    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"); } } 
    1. 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.
    2. We also did not have to clear the buffer using userInputScanner.nextLine(); in the catch part of the try-catch.
4 ★ | 2 Vote