Unit 1: Input

Table of Contents

  1. Scanner
  2. Scanner Methods

Scanner

Now that we’ve talked about how to display output to the user, let’s talk about how to get input from the user. To do this, you will need to import the Scanner class.

import java.util.Scanner;

Once you have imported the Scanner class, you can use Scanner methods. We’ll talk about methods later. For now, just think of methods as things you can use to accomplish a task. No need to worry about how it actually works.

For example, if I wanted to get the price of an apple from the user, I could do this:

import java.util.Scanner;

public class Input {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the price of an apple: $");
        double price = input.nextDouble();
        System.out.println("Apple price: $" + price);
    }
}

Example output:

Enter the price of an apple: $5.36 [Enter ↩]
Apple price: $5.36

Let’s break down this code. First, we imported the Scanner class using import java.util.Scanner;. Then we constructed a Scanner object using Scanner input = new Scanner(System.in);. Again, you don’t really need to know what objects are yet. Just know that whenever you want to get user input, you’ll need to do this. (Also note that input is simply the name that references the Scanner object, so you can name it whatever you want as long as you follow the identifier naming rules.)

Then you should display a prompt to the user which tells the user what input you want from them. (For example, System.out.print("Enter the price of an apple: ").) You should make this as specific as possible. Also, don’t forget to add a space after the prompt so that the cursor isn’t awkwardly next to the prompt.

Finally, you will need to get the input and store that value in a variable. You will need to assign a variable to the result of calling a method on the Scanner object you created. For example, double price = input.nextDouble();. Notice that the variable type should match the method that was called (nextDouble()). Also notice that to call the method, you need to use dot notation. That is, you need to use the variable that represents the Scanner object (in this case, we named it input), then a dot (.), and then the method.

Scanner Methods

Here are commonly used Scanner methods you should know:

Method Return Type Example Usage
nextInt() int input.nextInt();
nextDouble() double input.nextDouble();
nextLine() String input.nextLine();

Note that there is no nextChar() method.

Note that to close the input stream, you use the close() method. You technically don’t need to do this, put it’s generally good practice.