Java Reference
In-Depth Information
Display 6.1
An Array Used in a Program
(part 1 of 2)
1
import
java.util.Scanner;
2
public class
ArrayOfScores
3 {
4
/**
5
Reads in 5 scores and shows how much each
6
score differs from the highest score.
7
*/
8
public static void
main(String[] args)
9 {
10 Scanner keyboard =
new
Scanner(System.in);
11
double
[] score =
new double
[5];
12
int
index;
13
double
max;
14 System.out.println("Enter 5 scores:");
15 score[0] = keyboard.nextDouble();
16 max = score[0];
17
for
(index = 1; index < 5; index++)
18 {
19 score[index] = keyboard.nextDouble();
20
if
(score[index] > max)
21 max = score[index];
22
//max is the largest of the values score[0],
...
, score[index].
23 }
24 System.out.println("The highest score is " + max);
25 System.out.println("The scores are:");
26
for
(index = 0; index < 5; index++)
27 System.out.println(score[index] + " differs from max by "
28 + (max - score[index]));
29 }
30 }
Sample Dialogue
Enter 5 scores:
80 99.9 75 100 85.5
The highest score is 100
The scores are:
80.0 differs from max by 20
99.9 differs from max by 0.1
75.0 differs from max by 25
100.0 differs from max by 0.0
85.5 differs from max by 14.5
Due to imprecision in
floating-point arithmetic,
this value probably will only
be a close approximation to
0.1.
(continued)