Edit Article

Two Methods:VideosHandling Exceptions

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 is to use the Scanner object.

Ad

Method 1 of 2: Videos

  1. 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.
    
    Ad
  2. Get Input from a User in Java Step 2.jpg
    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. Get Input from a User in Java Step 3.jpg
    3
    You can now 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()
    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.print("\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. Get Input from a User in Java Step 4.jpg
    1
    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. Get Input from a User in Java Step 5.jpg
    2
    One way is to 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 the InputMismatchException 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.
  3. Get Input from a User in Java Step 6.jpg
    3
    Another way to make the user input foolproof is to only take 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.
    Ad


We could really use your help!

Can you tell us about
dogs?
Yes
No
dogs
how to keep your dog in shape
Can you tell us about
youth finance?
Yes
No
youth finance
how to make money when you are too young to get a job
Can you tell us about
bok choy?
Yes
No
bok choy
how to prepare bok choy
Can you tell us about
sunless tanning?
Yes
No
sunless tanning
how to remove sunless tanning
Thanks for helping! Please tell us everything you know about
...
Tell us everything you know here. Remember, more detail is better.
Tips
Provide Details.
Please be as detailed as possible in your explanation. Don't worry about formatting! We'll take care of it. For example:
Don't say: Eat more fats.
Do say: Add fats with some nutritional value to the foods you already eat. Try olive oil, butter, avocado, and mayonnaise.

Tips

  • See the Scanner API for more information on using the Scanner class.

Article Info

Categories: Java

Thanks to all authors for creating a page that has been read 67,343 times.

Did this article help you?
Yes No

Become
an Author!

Write an Article