Java Reference
In-Depth Information
Display 6.2
The
length
Instance Variable
The sample dialogue is the same as in
Display 6.1.
1
import
java.util.Scanner;
2
public
class
ArrayOfScores2
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 " + score.length + " scores:");
15
score[0] = keyboard.nextDouble();
16
max = score[0];
17
for
(index = 1; index < score.length; 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 < score.length; index++)
27
System.out.println(score[index] + " differs from max by "
28
+ (max
−
score[index]));
29
}
30
}
The
length
instance variable cannot be changed by your program (other than by
creating a new array with another use of
new
).
1
For example, the following is illegal:
score.length = 10;
//Illegal
1
The technical details are as follows: The instance variable
length
is created when the array is created
and is declared to be
public final int
.