(^484) | One-Dimensional Arrays
// Write 1,000 values
outFile.println(value999);
outFile.println(value998);
outFile.println(value997);
.
.
.
outFile.println(value0);
inFile.close();
outFile.close();
}
}
This application is more than 3,000 lines long, and we have to use 1,000 separate variables.
Note that all the variables have the same name except for an appended number that dis-
tinguishes them. Wouldn’t it be more convenient if we could put the number into a counter
variable and use forloops to go from 0 through 999, and then from 999 back down to 0? For
example, if the counter variable were number, we could replace the 2,000 original input/out-
put statements with the following four lines of code (we enclose numberin brackets to set it
apart from value):
for (number = 0; number < 1000; number++)
value[number] = Integer.parseInt(inFile.readLine());
for (number = 999; number >= 0; number--)
outFile.println(value[number]);
This code fragment is correct in Java ifwe declare valueto be a one-dimensional array. Such an
array is a collection of variables—all of the same type—where the first part of each variable
name is the same, and the last part is an index value.
The declaration of a one-dimensional array is similar to the declaration of a simple vari-
able (a variable of a simple data type), with one exception: You must indicate that it is an ar-
ray by putting square brackets next to the type.
int[] value;
Because an array is a reference type, it must be instantiated. At that time, we must spec-
ify the size of the array.
value = new int[1000];
Herevaluerepresents an array with 1,000 components, all of typeint.The first component has
index value 0 , the second component has index value 1 , and the last component has index value
999.
The following application prints out numbers in reverse order using an array. It is cer-
tainly much shorter than our first version of the application.
やまだぃちぅ
(やまだぃちぅ)
#1