Programming and Problem Solving with Java

(やまだぃちぅ) #1
10.3 One-Dimensional Arrays | 483

10.3 One-Dimensional Arrays


How we organize our data plays an important role in the design process. If the internal data
representation for a class is a composite type (that is, if it contains more than a single atomic
field), we call the internal representation a data structure. The choice of data struc-
ture directly affects the design because it determines the algorithms used to
process the data. The class gives us the ability to refer to an entire group of com-
ponents by one name, which simplifies the design of many applications.
Many problems, however, have so many components that it is difficult to
process them if each one must have a unique field name. For example, if we use
individually named values to read and print a file in reverse order, all the values
must be read and saved before the last one can be printed. If there are 1,000 values, we must
define 1,000 individual variables to hold the values and input and output each value sepa-
rately—an incredibly tedious task! An array—the last of Java’s built-in reference types—is the
data type that allows us to program operations of this kind with ease.
Let’s look at how we would have to solve this problem with simple variables.


// Read 1,000 numbers and print them in reverse order
importjava.io.*;
public classArrayExample
{
public static voidmain(String[] args) throwsIOException
{
BufferedReader inFile;
PrintWriter outFile;
inFile = new BufferedReader(new FileReader("infile.dat"));
outFile = new PrintWriter(new FileWriter("outfile.dat"));


// Declare 1,000 integer variables
int value0;
int value1;
int value2;
.
.
.
int value999;

// Read 1,000 integer values
value0 = Integer.parseInt(inFile.readLine());
value1 = Integer.parseInt(inFile.readLine());
value2 = Integer.parseInt(inFile.readLine());
.
.
.
value999 = Integer.parseInt(inFile.readLine());

Data structure The implemen-
tation of a composite data field
in an abstract data type
Free download pdf