7. Getting user input

A sample program

Here's a program that will get input from the user and print it. I've added the equivalent Python program for comparison.

// java
import java.util.Scanner;
class GettingUserInput {
    public static void main(String[] args) {
        Scanner userInput;
        userInput = new Scanner(System.in);

        System.out.println("Please type your name."); 
        String userName = userInput.nextLine();

        System.out.println("Your name is: " + userName);
# python

def main():


    user_input = input("Please type your name.\n")  

    print("Your name is:", user_input)


That's a lot of code just to get input, huh? Run it yourself to see exactly what it does.

Now, let's see how it works line by line.


import java.util.Scanner;

In Java, classes are organized into packages. The java.lang package (which contains the String class) is automatically imported into any programs you write. But if you want classes from any other package, you'll have to import them.

This import statement looks inside the java.util package for the Scanner class. Import statements go at the top of the program, outside of the class.

Constructing a Scanner object

The Scanner class is used to prompt for user input, much like Python's input function. When certain methods (like nextLine) are called on a Scanner object, the object will halt the program and wait for the user to type something. When the user presses enter, it'll return whatever the user typed and resume program execution.

Let's take a closer look at our Scanner object.

Scanner userInput;

This line declares an object of type Scanner named userInput. It's the same thing as declaring any other type of variable

int x;

only now the type is Scanner instead of String, or int, or any of the other primitive types.

But how do we actually create a Scanner object? With the primitive types and String, we just assign a literal data value:

int x = 5;              // puts a 5 inside x directly
String y = "abcdef";    // puts the string "abcdef" in y
boolean z = true;       // puts true inside z - no object construction needed

But there's no Scanner data value. Instead, we have to tell Java to construct a Scanner object. We can do this by using the new keyword, followed by the class name and whatever arguments the class's constructor takes (in this case, System.in, which is the keyboard input stream).

userInput = new Scanner(System.in);

Now, userInput is a Scanner object, and we can call Scanner methods on it.

If you're confused about object construction and need a review, we'll cover that later.

Calling methods on our Scanner objects

String userName = userInput.nextLine();

This line reaches inside the userInput Scanner object and calls its nextLine method on it. nextLine halts the program, waits for the user to type something, and returns whatever the user typed as a string. We then put that returned string inside a String variable named userName.

This code only works because the Scanner class has a nextLine method defined inside of it. We can't do this on Strings or ints:

// won't compile, these methods aren't defined for these types
String x = "abc";
x.nextLine(); // bad
int y = 345;
y.nextLine(); // bad


These exercises will help you learn more about Scanner and taking input. Even though some things might not make sense yet, don't let that stop you - take your confusions one at a time and try to resolve them. If one of your confusions is particularly stubborn, leave it and come back to it later. You'll figure it out eventually.

  1. Debug this program:

    class InputGetStuff() {
        public static void main(String args) {
            Scanner x = Scanner();
            System.out.println("What's your favorite food?");
            System.out.println("You like " + userFood);
  2. Read about the Scanner class by googling java API scanner. API stands for Application Programming Interface and a class's API page documents its methods and variables. What other methods does the Scanner class have? What do they do?

    Don't worry if most of what's in the API page doesn't make sense yet. With more practice, you'll get more comfortable with the vocabulary.

  3. Write a program that gets the user's age and converts it to dog years (divides it by 7).

    Since nextLine returns a String, you'll have to do convert what the user types to an int or use a different method besides nextLine to get the input.

  4. Why don't we use the new keyword when making an int, double, boolean, or String? Google around and see if you can figure it out. Even if you can't find an answer you completely understand, you'll still learn something.