Java Reference
In-Depth Information
16 System.out.println( "The area for the circle of radius " +
17 radius + " is " + area);
18 }
19 }
Enter a number for radius: 2.5
The area for the circle of radius 2.5 is 19.6349375
Enter a number for radius: 23
The area for the circle of radius 23.0 is 1661.90111
Line 9 displays a string "Enter a number for radius: " to the console. This is
known as a prompt , because it directs the user to enter an input. Your program should always
tell the user what to enter when expecting input from the keyboard.
The print method in line 9
System.out.print( "Enter a number for radius: " );
is identical to the println method except that println moves to the beginning of the next
line after displaying the string, but print does not advance to the next line when completed.
Line 6 creates a Scanner object. The statement in line 10 reads input from the keyboard.
double radius = input.nextDouble();
prompt
print vs. println
After the user enters a number and presses the Enter key, the program reads the number
and assigns it to radius .
More details on objects will be introduced in Chapter 9. For the time being, simply accept
that this is how to obtain input from the console.
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 spec-
ifies a single class in the import statement. For example, the following statement imports
Scanner from the package java.util .
import java.util.Scanner;
specific import
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.
Listing 2.3 gives an example of reading multiple input from the keyboard. The program
reads three numbers and displays their average.
wildcard import
no performance difference
L ISTING 2.3
ComputeAverage.java
1 import java.util.Scanner; // Scanner is in the java.util package
2
3 public class ComputeAverage {
4
import class
public static void main(String[] args) {
5
// Create a Scanner object
6
Scanner input = new Scanner(System.in);
create a Scanner
7
 
 
Search WWH ::




Custom Search