DEV Community

Edwin Torres
Edwin Torres

Posted on

Simple Java Scanner Tutorial

Introduction

This is a simple tutorial on using the Scanner class in Java. The Scanner class lets you accept input from the console. The user types on the keyboard and passes that data to the program.

Prerequisites

  • Install Java and Visual Studio (VS) Code. Here is a tutorial: Tutorial: Visual Studio Code and Java.
  • Start VS Code.
  • Create a new Java project as specified in the tutorial.
  • In the left sidebar, right-click the src folder and select New File. Create a file named Example.java.
  • Continue to the tutorial below.

Code

In the left sidebar in VS Code, click the Example.java file to show it in the main editor window. Enter this initial code:

public class Example {
  public static void main(String[] args) {


  }
}
Enter fullscreen mode Exit fullscreen mode

To use the Scanner class, import it at the top of the program:

import java.util.Scanner; // NEW

public class Example {
  public static void main(String[] args) {


  }
}
Enter fullscreen mode Exit fullscreen mode

Next, create a Scanner object to read from standard input (i.e., the console):

import java.util.Scanner;

public class Example {
  public static void main(String[] args) {

    Scanner s = new Scanner(System.in); // NEW

  }
}
Enter fullscreen mode Exit fullscreen mode

Now prompt the user to enter some data from the keyboard:

import java.util.Scanner;

public class Example {
  public static void main(String[] args) {

    Scanner s = new Scanner(System.in);

    System.out.print("What is your favorite number? "); // NEW

  }
}
Enter fullscreen mode Exit fullscreen mode

Use the Scanner object to accept an integer value from standard input and assign it to a variable:

import java.util.Scanner;

public class Example {
  public static void main(String[] args) {

    Scanner s = new Scanner(System.in);

    System.out.print("What is your favorite number? ");

    int num = s.nextInt(); // NEW

  }
}
Enter fullscreen mode Exit fullscreen mode

The num variable holds the input data. Output the num variable to verify:

import java.util.Scanner;

public class Example {
  public static void main(String[] args) {

    Scanner s = new Scanner(System.in);

    System.out.print("What is your favorite number? ");

    int num = s.nextInt();

    System.out.println("Your favorite number is: " + num); // NEW

  }
}
Enter fullscreen mode Exit fullscreen mode

Here is a sample run of the program from the terminal:

What is your favorite number? 44
Your favorite number is: 44
Enter fullscreen mode Exit fullscreen mode

Additional Exercise

  • Modify the program to ask the user for an age and day of the month.
  • Output the age and day of the month.

Thanks for reading.

Follow me on Twitter @realEdwinTorres for more programming tips. 😀

Top comments (0)