1 import java.util.Scanner;
2
3 public class ArrayDemo
4 {
5 public static void main(String[] args)
6 {
7 // An array of five values, initialized in a loop
8
9 int[] values = new int[5];
10 for (int i = 0; i < values.length; i++)
11 {
12 values[i] = 2 * i;
13 }
14
15 // An array of four strings, with initial values specified
16
17 String[] names = { "Fred", "Amy", "Cindy", "Henry" };
18
19 // These loops print the elements in both arrays
20
21 for (int i = 0; i < values.length; i++)
22 {
23 System.out.print(values[i] + " ");
24 }
25 System.out.println();
26
27 for (int i = 0; i < names.length; i++)
28 {
29 System.out.print(names[i] + " ");
30 }
31 System.out.println();
32
33 // When you copy an array variable, you get another reference
34 // to the same array. (See Section 7.1.2.)
35
36 int[] copy = values;
37 values[0] = 42;
38 // We change values[0], which is the same as copy[0]
39
40 for (int i = 0; i < copy.length; i++)
41 {
42 System.out.print(copy[i] + " ");
43 }
44 System.out.println();
45
46 // Here, we read numbers into a partially filled array.
47 // (See Section 7.1.4.)
48
49 System.out.println("Enter scores, -1 to quit: ");
50 Scanner in = new Scanner(System.in);
51 boolean done = false;
52 int currentSize = 0;
53 final int LENGTH = 100;
54 int[] scores = new int[LENGTH];
55
56 while (!done && currentSize < LENGTH)
57 {
58 int score = in.nextInt();
59 if (score == -1)
60 {
61 done = true;
62 }
63 else
64 {
65 scores[currentSize] = score;
66 currentSize++;
67 }
68 }
69
70 System.out.println("You entered the following scores:");
71 for (int i = 0; i < currentSize; i++)
72 {
73 System.out.print(scores[i] + " ");
74 }
75 System.out.println();
76 }
77 }