...

/

Simple Input from the Keyboard

Simple Input from the Keyboard

In this lesson, we will explore how a Java program reads integers and real numbers entered by a user.

The class Scanner

A Java program can read data from either the keyboard or another source, such as a disk, and place it into memory. The programs in this course will use the keyboard as their input device.

The Java Class Library provides the class Scanner that we read data typed at the keyboard and place it into variables that we specify.

The Java Class Library is organized into units called packages. The class Scanner, for example, is in the package java.util. To use Scanner in our program, we must tell the compiler where to find the class. One way to do so is to write the class’s name as java.util.Scanner each time we need to use it. This fully qualified name is tedious to write over and over again, so Java provides another way. We can write the following import statement before the rest of our program:

import java.util.Scanner;

This statement tells the compiler to look in the package java.util for the class Scanner. Then, anytime we write Scanner in our program, the compiler will understand it as java.util.Scanner. As we ...

Access this course and 1400+ top-rated courses and projects.