Learn

Just like System, the Scanner class is predefined and built into Java for your use. It’s used to read user input in a Java program.

For this exercise, we will build a program that walks us through writing code that uses the Scanner class together. Before we can code our own class, we must import the Scanner class, which you can do using the following:

import java.util.Scanner;

Let’s begin by declaring the Scanner class as a variable that we will call input:

Scanner input = new Scanner(System.in);

Notice how we have placed System.in within the brackets in our declaration. This is what will allow our program to read user input from the console. The Scanner class can also read input from a file; we will cover that in the next exercise.

Next, let’s take a look at the code that is required to read user input. The Scanner class can read different types of values that can be saved into different variable types. The list below outlines some (but not all) the different variable types and the code required to read the variables into the program:

Variable Code
Int int num = input.nextInt();
Double double numDouble = input.nextDouble();
Byte byte numByte = input.nextByte();
Boolean boolean isTrue = input.nextBoolean();
Long long numLong = input.nextLong();
Short short numShort = input.nextShort();

The Scanner class has many functions, including the ability to validate and convert variables. Some examples include:

Code Function
input.hasNextLine() This function returns a boolean that validates if there is another line in the input of the defined scanner.
input.hasNextInt() This function returns a boolean that validates if there is another int in the input of the defined scanner.
input.useDelimiter(","): This function helps us specify what delimiters we want to use. A delimiter is used to separate data units. Delimiters can be especially useful when a program is required to read csv files.
num.toString() This function can be used to convert different variable types to string variables. In this example, we are converting an int to a string.

Instructions

1.

Import the Scanner class at the top of your program, then declare the Scanner in the main() method.

2.

Now we can begin interacting with the program!

Write the print statement that asks the user what their name is. Then use .next() to save their answer to the variable userName.

3.

Use System.out.printf() to print the following statement:

Hello "userName"! It's nice to meet you.

where “userName” is replaced with the input provided by the user.

4.

Now let’s test it out! First, compile your program using the correct command in the terminal.

5.

Now, run your program using the correct command in the terminal.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?