You are on page 1of 10

Lesson Set Arrays and Collections

7
Purpose 1. Manipulate a collection of data values, using
an array
2. Define a method that accepts an array as its
parameter and a method that returns an array.
3. Describe how a two-dimensional array is
implemented as an array of arrays.
4. Manipulate a collection of objects, using lists
and maps.

Procedure 5. Students should read the Pre-lab Reading Assignment


before coming to lab.
6. Students should complete the Pre-lab Writing Assignment
before coming to lab.
7. In the lab, students should complete Labs 1.1 through 1.4
in sequence.
8. Your instructor will give further instructions as to grading
and completion of the lab.
9. Students should complete the set of lab tasks before the
next lab and get them checked by their lab instructor.

Contents Pre-requisites Completion


Time

Pre-lab Reading Assignment - 10 min

Lab 1 Basic 30 min


Tracking Sales understanding of
1D Array

Lab 2 Basic 30 min


Grading Quiz understanding of
looping in an array

Lab 3 Basic 30 min


Reversing Array understanding of
looping in an array

Introduction: People collect all sorts of items from bottle caps to exotic cars. For proof, just go
toeBay (www.ebay.com) and see millions and millions of collectibles up for
auction.

With computers, people amass intangible items such as music files. Exactly how
many MP3 files do you have on your computer? Probably in the hundreds and
you
lost track of exactly how many. You may want to develop a custom software, so
you can store the information you want in the format you like, to keep track of all
MP3 files downloaded from the Web.

When we write a program to deal with a collection of items, say, 500 Student
objects, 200 integers, 300 MP3 files, and so forth, simple variables will not work.
It is just not practical or feasible to use 500 variables to process 500 Student
objects.
In theory, you can, but honestly, do you want to type in identifiers for 500
variables
(student1, student2, . . .)? A feature supported by programming languages to
manipulate a collection of values is an array. In this chapter we will learn about
Java arrays. We will learn the basics of array manipulation and how to use
different types of arrays properly and effectively. In addition, we will study
Array Basics: several collection classes from the java.util package that provide more advanced
data management features not found in the basic Java arrays.

Suppose we want to compute the annual average rainfall from 12 monthly


averages. We can use three variables and compute the annual average as follows
(in this and other code fragment examples, we assume scanner is a properly
declared and created Scanner object):

double sum, rainfall, annualAverage;


sum = 0.0;
for (int i = 0; i < 12; i++) {
System.out.print("Rainfall for month " + (i+1) + ": ");
rainfall = scanner.nextDouble();
sum += rainfall;
}
annualAverage = sum / 12.0;
Now suppose we want to compute the difference between the annual and
monthly averages for every month and display a table with three columns, similar
to the one shown in Figure 10.1.
Array:
To compute the difference between the annual and monthly averages, we need
to remember the 12 monthly rainfall averages. Without remembering the 12
monthly averages, we won’t be able to derive the monthly variations after the
annual average is computed. Instead of using 12 variables januaryRainfall,
februaryRainfall, and so forth to solve this problem, we use an array.
Array Decleration:
An array is a collection of data values of the same type. For example, we may
declare an array consisting of double, but not an array consisting of both int and
double. The following declares an array of double:
double[] rainfall;

The square brackets indicate the array declaration. The brackets may be attached
to
a variable instead of the data type. For example, the declaration
double rainfall[];
is equivalent to the previous declaration. In Java, an array is a reference data type.
Unlike the primitive data type, the amount of memory allocated to store an array
varies, depending on the number and type of values in the array. We use the new
operator to allocate the memory to store the values in an array. Although we use
the same reserved word new for the array memory allocation as for the creation of
a new instance of a class, strictly speaking, an array is not an object.
The following statement allocates the memory to store 12 double values and
associates the identifier rainfall to it.
rainfall = new double[12]; //create an array of size 12
Figure 10.2 shows this array.
Fixed sizearray
declearion:
We can also declare and allocate memory for an array in one statement, as in
double[] rainfall = new double[12];

Using constants to declare array sizes does not always lead to efficient space
usage. We call the declaration of arrays with constants a fixed-size array
declaration. There are two potential problems with fixed-size array declarations.
Suppose, for example, we declare an integer array of size 100:
int[] number = new int[100];
The first problem is that the program can process only up to 100 numbers. What
if we need to process 101 numbers? We have to modify the program and compile
it again. The second problem is a possible underutilization of space. The above
declaration allocates 100 spaces whether they are used or not
Lab Tasks

1. File Sales.java contains a Java program that prompts for and reads in the sales for each of 5 salespeople in a
company. It then prints out the id and amount of sales for each salesperson and the total sales. Study the
code, then compile and run the program to see how it works. Now modify the program as follows:

1. Compute and print the average sale. (You can compute this directly from the total; no loop is necessary.)
2. Find and print the maximum sale. Print both the id of the salesperson with the max sale and the amount
of the sale, e.g., "Salesperson 3 had the highest sale with $4500." Note that you don't need another loop for
this; you can do it in the same loop where the values are read and the sum is computed.
3. Do the same for the minimum sale.
4. After the list, sum, average, max and min have been printed, ask the user to enter a value. Then print the
id of each salesperson who exceeded that amount, and the amount of their sales. Also print the total number
of salespeople whose sales exceeded the value entered.
5. The salespeople are objecting to having an id of 0—no one wants that designation. Modify your program
so that the ids run from 1–5 instead of 0–4. Do not modify the array—just make the information for
salesperson 1 reside in array location 0, and so on.
6. Instead of always reading in 5 sales amounts, at the beginning ask the user for the number of sales people
and then create an array that is just the right size. The program can then proceed as before.
2. Write a program that grades arithmetic quizzes as follows:
1. Ask the user how many questions are in the quiz.
2. Ask the user to enter the key (that is, the correct answers). There should be one answer for
each question in the quiz, and each answer should be an integer. They can be entered on a
single line, e.g., 34 7 13 100 81 3 9 10 321 12 might be the key for a 10-question quiz. You will
need to store the key in an array.
3. Ask the user to enter the answers for the quiz to be graded. As for the key, these can be
entered on a single line. Again there needs to be one for each question. Note that these answers
do not need to be stored; each answer can simply be compared to the key as it is entered.
4. When the user has entered all of the answers to be graded, print the number correct and the
percent correct.
When this works, add a loop so that the user can grade any number of quizzes with a single key.
After the results have been printed for each quiz, ask "Grade another quiz? (y/n)."
3. Write a program that prompts the user for an integer, then asks the user to enter that many
values. Store these values in an array and print the array. Then reverse the array elements so
that the first element becomes the last element, the second element becomes the second to
last element, and so on, with the old last element now first.

You might also like