Please enable JavaScript to use CodeHS

User Input in Java

Learn how to accept user input in Java.

By Evelyn Hunter

An important aspect of computer science is creating interactive programs for users. A large part of user interaction is allowing users to input information into a program.

In Java, the Scanner class is often used to get information from users.

The Scanner class is a pre-built class within java.util that contains code specifically designed to help with user input. To make use of the Scanner class, it needs to be imported to whichever class is using it:

import java.util.Scanner;

public class UserInput
{}
Plain text

Once the Scanner class has been imported, a Scanner object needs to be created to receive input:

import java.util.Scanner;

public class UserInput
{
   public static void main(String[] args)
   {
         Scanner input = new Scanner(System.in);
   }
}
Plain text

The parameter System.in specifies the source of the input stream. In most cases, that corresponds to the keyboard. The Scanner object can now be used to get user input. There are several methods that can be used to retrieve user input:

input.nextInt(): Reads an int value from user.
input.nextDouble(): Reads a double value from user.
input.nextBoolean(): Reads a boolean value from user.
input.nextLine(): Reads a String value from user.

Once a value has been read from a user, it can be stored in a variable for future use:

User Input with CodeHS Console

CodeHS also offers an extended console class that makes it easier to get input from users. The ConsoleProgram class from CodeHS offers prebuilt methods that eliminate the need to use the Scanner class or importing the java.util package:

readInt(prompt): Reads an int value from user.
readDouble(prompt): Reads a double value from user.
readBoolean(prompt): Reads a boolean value from user.
readLine(prompt): Reads a String value from user.

Rather than use the System.out.println to prompt users, the readLine method accepts a prompt as a parameter, which automatically prints to the console when executed:

The ConsoleProgram class is used throughout the CodeHS Mocha course and can be created using the Sandbox.

Practice!

In the following program, use the Scanner class to prompt a user to input their age. Then, print back to the console the age that they will be in 15 years! The results may look like this:

How old are you?
15
In 15 years, you'll be 30!
Plain text