Reading Input from the Console
Paul Ngugi
Posted on April 24, 2024
Reading input from the console enables the program to accept input from the user. Java uses System.out to refer to the standard output device and System.in to the standard input device. By default, the output device is the display monitor and the input device is the keyboard. To perform console output, you simply use the println method to display a primitive value or a string to the console. Console input is not directly supported in Java, but you can use the Scanner class to create an object to read input from System.in, as follows:
Scanner input = new Scanner(System.in);
The syntax new Scanner(System.in) creates an object of the Scanner type. The syntax Scanner input declares that input is a variable whose type is Scanner. The whole line Scanner input = new Scanner(System.in) creates a Scanner object and assigns its reference to the variable input. An object may invoke its methods. To invoke a method on an object is to ask the object to perform a task. You can invoke the nextDouble() method to read a double value as follows:
double radius = input.nextDouble();
This statement reads a number from the keyboard and assigns the number to radius
After the user enters a number and presses the Enter key, the program reads the number and assigns it to radius.
The Scanner class is in the java.util package. It is imported in line 1. There are two types of import statements: specific import and wildcard import. The specific import specifies a single class in the import statement. For example, the following statement imports Scanner from the package java.util.
import java.util.Scanner;
The wildcard import imports all the classes in a package by using the asterisk as the wildcard. For example, the following statement imports all the classes from the package
java.util.
import java.uitl.*;
The information for the classes in an imported package is not read in at compile time or runtime unless the class is used in the program. The import statement simply tells the compiler where to locate the classes. There is no performance difference between a specific import and a wildcard import declaration.
You may enter three numbers separated by spaces, then press the Enter key, or enter each number followed by a press of the Enter key, as shown in the sample runs of this program. If you entered an input other than a numeric value, a runtime error would occur.
Posted on April 24, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.