Menu
Coddy logo textTech

Scanner Class

Part of the Fundamentals section of Coddy's Java journey — lesson 35 of 73.

As of now we stored values that we thought about in variables. Programs usually don't work this way. We receive values from an outer source, a user for example.

In Java, getting input from a user is done using the Scanner class. This class provides methods to read different types of input, such as integers, floating-point numbers, and strings.

To use the Scanner class, you first need to create an instance of it and associate it with the standard input stream System.in. Here's how you do it:

Scanner scanner = new Scanner(System.in);

Once you have a Scanner object, you can use its methods to read input.

Here are some commonly used methods:

  • nextInt(): Reads an integer.
  • nextDouble(): Reads a double.
  • nextLine(): Reads a line of text (string).

Here's an example of how to get input from a user:

Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Your age is: " + age);

In this example, the program prompts the user to enter their age, reads the integer using nextInt(), and then prints it back to the console.

After you're done with the Scanner, it's a good practice to close it using scanner.close() to release the resources associated with it.

challenge icon

Challenge

Beginner

Write a program that gets input from the user (their name), and then outputs Hello, followed by the user's inputted name.

For example, if the user inputs Bob, the expected output is Hello, Bob.

You will need to:

  1. Create a Scanner object to read input.
  2. Prompt the user to enter their name using exactly: Enter your name:
  3. Read the user's name using the appropriate Scanner method.
  4. Print Hello, and the stored variable in the end.

Cheat sheet

To get user input in Java, use the Scanner class:

Scanner scanner = new Scanner(System.in);

Common Scanner methods:

  • nextInt(): Reads an integer
  • nextDouble(): Reads a double
  • nextLine(): Reads a line of text (string)

Example of reading user input:

Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Your age is: " + age);

Close the scanner when done to release resources:

scanner.close();

Try it yourself

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Create a Scanner object
        Scanner scanner = new Scanner(System.in);
        
        // Prompt the user to enter their name
        
        
        // Read the user's name
        
        
        // Print the greeting message
        
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals