Java Reference
In-Depth Information
8 // Prompt the user to enter three numbers
9 System.out.print( "Enter three numbers: " );
10
double number1 = input.nextDouble();
read a double
11
double number2 = input.nextDouble();
12
double number3 = input.nextDouble();
13
14
// Compute average
15
double average = (number1 + number2 + number3) / 3 ;
16
17 // Display results
18 System.out.println( "The average of " + number1 + " " + number2
19 + " " + number3 + " is " + average);
20 }
21 }
Enter three numbers: 1 2 3
The average of 1.0 2.0 3.0 is 2.0
enter input in one line
Enter three numbers: 10.5
11
11.5
The average of 10.5 11.0 11.5 is 11.0
enter input in multiple lines
The code for importing the Scanner class (line 1) and creating a Scanner object (line
6) are the same as in the preceding example as well as in all new programs you will write for
reading input from the keyboard.
Line 9 prompts the user to enter three numbers. The numbers are read in lines 10-12. 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. In Chapter 12,
you will learn how to handle the exception so that the program can continue to run.
runtime error
Note
Most of the programs in the early chapters of this topic perform three steps—input,
process, and output—called IPO. Input is receiving input from the user; process is pro-
ducing results using the input; and output is displaying the results.
IPO
2.2
How do you write a statement to let the user enter a double value from the keyboard?
What happens if you entered 5a when executing the following code?
double radius = input.nextDouble();
Check
Point
2.3
Are there any performance differences between the following two import statements?
import java.util.Scanner;
import java.util.*;
2.4 Identifiers
Identifiers are the names that identify the elements such as classes, methods, and
variables in a program.
Key
Point
As you see in Listing 2.3, ComputeAverage , main , input , number1 , number2 , number3 ,
and so on are the names of things that appear in the program. In programming terminology,
such names are called identifiers. All identifiers must obey the following rules:
identifiers
identifier naming rules
An identifier is a sequence of characters that consists of letters, digits, underscores
( _ ), and dollar signs ( $ ).
 
 
 
Search WWH ::




Custom Search