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 introduce
other classes in the Java Class Library, we will show you the appropriate import
statement to use.
📝 Syntax: The
import
statementTo use a class from the Java Class Library, you can write an
import
statement before the rest of the program, including its initial comments. This statement has the following form:Assuming that a statement such as:
import package-name.class-name
It allows you to use just the class name within the program instead of its fully qualified name, package-name
.
class-name. Although you can avoidimport
statements by always using fully qualified class names, most programmers do useimport
statements.
Scanner
objects
Before we can use any of the methods in Scanner
, we must create a Scanner
object by writing a statement such as
Scanner keyboard = new Scanner(System.in);
This statement assigns the Scanner
object associated with the input device that System.in
represents to the variable keyboard
—which could have any name of our choosing. This input device, by convention, is the keyboard.
Scanner
methods
Scanner
provides several methods that read input data. We can use any of these methods by writing a statement that has the following form, where keyboard
is the Scanner
object that we defined previously:
variable = keyboard.method_name();
The named method reads a value from the keyboard and returns it. That is the expression keyboard.
method_name()
represents the value that was read. The previous statement then assigns this value to the indicated variable.
Data, like Java statements, can contain white space. Any cluster of symbols other than white space is called a token. A Scanner
object identifies these tokens and converts them into values of various
data types according to the Scanner
method we use.
Get hands-on with 1400+ tech skills courses.