Chapter 8: Arrays 123
Chapter 8: Arrays
Lab Exercises
Topics Lab Exercises
One-Dimensional Arrays Tracking Sales
Grading Quizzes
Reversing an Array
Adding To and Removing From an Integer List
Arrays of Objects A Shopping Cart
Polygons & Polylines A Polygon Person
Arrays & GUIs An Array of Radio Buttons
Chapter 8: Arrays 124
Tracking Sales
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:
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.,
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
5. The salespeople are objecting to having an id of 0—no one wants that designation. Modify your program so that the ids
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.
// ***************************************************************
// Sales.java
// ***************************************************************
import java.util.Scanner;
public class Sales
{
public static void main(String[] args)
{
final int SALESPEOPLE = 5;
int[] sales = new int[SALESPEOPLE];
System.out.println(“\nSalesperson Sales”);
System.out.println(” —————— “);
sum = 0;
for (int i=0; i<sales.length; i++)
Grading Quizzes
Write a program that grades arithmetic quizzes as follows:
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
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
4. When the user has entered all of the answers to be graded, print the number correct and the percent correct.
Chapter 8: Arrays 126
Reversing an Array
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. Do not just reverse the order in
Adding To and Removing From an Integer List
File IntegerList.java contains a Java class representing a list of integers. The following public methods are provided:
IntegerList(int size)—creates a new list of size elements. Elements are initialized to 0.
File IntegerListTest.java contains a Java program that provides menu-driven testing for the IntegerList class. Copy both files
to your directory, and compile and run IntegerListTest to see how it works.
It is often necessary to add items to or remove items from a list. When the list is stored in an array, one way to do this is to
create a new array of the appropriate size each time the number of elements changes, and copy the values over from the old
array. However, this is rather inefficient. A more common strategy is to choose an initial size for the array and add elements
until it is full, then double its size and continue adding elements until it is full, and so on. (It is also possible to decrease the
size of the array if it falls under, say, half full, but we won’t do that in this exercise.) The CDCollection class in Listing 7.8 of
the text uses this strategy—it keeps track of the current size of the array and the number of elements already stored in it, and
method addCD calls increaseSize if the array is full. Study that example.
1. Add this capability to the IntegerList class. You will need to add an increaseSize method plus instance variables to hold
2. Add a method void addElement(int newVal) to the IntegerList class that adds an element to the list. At the beginning of
3. Add a method void removeFirst(int newVal) to the IntegerList class that removes the first occurrence of a value from the
list. If the value does not appear in the list, it should do nothing (but it’s not an error). Removing an item should not
4. Add a method removeAll(int newVal) to the IntegerList class that removes all occurrences of a value from the list. If the
value does not appear in the list, it should do nothing (but it’s not an error).
Add an option to the menu in IntegerListTest to test your new method.
// ***************************************************************
// IntegerList.java
//
{
list = new int[size];
}
//——————————————————-
//fill array with integers between 1 and 100, inclusive
//——————————————————-
public void randomize()
{
//
// Provide a menu-driven tester for the IntegerList class.
//
// ***************************************************************
import java.util.Scanner;
public class IntegerListTest
{
static IntegerList list = new IntegerList(10);
printMenu();
choice = scan.nextInt();
}
}
//————————————-
// Do what the menu item calls for
//————————————-
{
case 0:
case 1:
System.out.println(“How big should the list be?”);
case 2:
list.print();
break;
default:
System.out.println(“Sorry, invalid choice”);
}
}
Chapter 8: Arrays 130
A Shopping Cart
In this exercise you will complete a class that implements a shopping cart as an array of items. The file Item.java contains the
definition of a class named Item that models an item one would purchase. An item has a name, price, and quantity (the
quantity purchased). The file ShoppingCart.java implements the shopping cart as an array of Item objects.
1. Complete the ShoppingCart class by doing the following:
a. Declare an instance variable cart to be an array of Items and instantiate cart in the constructor to be an array holding
2. Write a program that simulates shopping. The program should have a loop that continues as long as the user wants to
shop. Each time through the loop read in the name, price, and quantity of the item the user wants to add to the cart. After
adding an item to the cart, the cart contents should be printed. After the loop print a “Please pay …” message with the
total price of the items in the cart.
// ***************************************************************
// —————————————————–
public Item (String itemName, double itemPrice, int numPurchased)
{
name = itemName;
price = itemPrice;
quantity = numPurchased;
}
public double getPrice()
{
return price;
}
// ———————————————–
// Returns the name of the item
//
// Represents a shopping cart as an array of items
// ***************************************************************
import java.text.NumberFormat;
public class ShoppingCart
{
private int itemCount; // total number of items in the cart
// Adds an item to the shopping cart.
// —————————————————–
public void addToCart(String itemName, double price, int quantity)
{
}
// —————————————————–
// Returns the contents of the cart together with
contents += “\n”;
return contents;
}
// —————————————————–
// Increases the capacity of the shopping cart by 3
// —————————————————–
Chapter 8: Arrays 133
Averaging Numbers
As discussed in Section 7.4 of the text book, when you run a Java program called Foo, anything typed on the command line
after “java Foo” is passed to the main method in the args parameter as an array of strings.
1. Write a program Average.java that just prints the strings that it is given at the command line, one per line. If nothing
is given at the command line, print “No arguments”.
2. Modify your program so that it assumes the arguments given at the command line are integers. If there are no
arguments, print a message. If there is at least one argument, compute and print the average of the arguments. Note
3. Test your program thoroughly using different numbers of command line arguments.
Exploring Variable Length Parameter Lists
The file Parameters.java contains a program to test the variable length method average from Section 7.5 of the text. Note
that average must be a static method since it is called from the static method main.
2. Add a call to find the average of a single integer, say 13. Print the result of the call.
3. Add a call with an empty parameter list and print the result. Is the behavior what you expected?
4. Add an interactive part to the program. Ask the user to enter a sequence of at most 20 nonnegative integers. Your
program should have a loop that reads the integers into an array and stops when a negative is entered (the negative
number should not be stored). Invoke the average method to find the average of the integers in the array (send the
array as the parameter). Does this work?
//*******************************************************
// Parameters.java
//
// Illustrates the concept of a variable parameter list.
mean2 = average(35, 43, 93, 23, 40, 21, 75);
System.out.println (“mean1 = ” + mean1);
System.out.println (“mean2 = ” + mean2);
}
//———————————————-
// Returns the average of its parameters.
Magic Squares
One interesting application of two-dimensional arrays is magic squares. A magic square is a square matrix in which the sum
of every row, every column, and both diagonals is the same. Magic squares have been studied for many years, and there are
some particularly famous magic squares. In this exercise you will write code to determine whether a square is magic.
File Square.java contains the shell for a class that represents a square matrix. It contains headers for a constructor that gives
// Square.java
//
// Define a Square class with methods to create and read in
// info for a square matrix and to compute the sum of a row,
// a col, either diagonal, and whether it is magic.
//
// ***************************************************************
public int sumRow(int row)
{
}
//————————————–
//return the sum of the values in the given column
//————————————–
public int sumCol(int col)
{
}
Chapter 8: Arrays 136
//return true if the square is magic (all rows, cols, and diags have
//same sum), false otherwise
//————————————–
public boolean magic()
{
}
//————————————–
public void printSquare()
{
}
}
// ***************************************************************
// SquareTest.java
//
// Uses the Square class to read in square data and tell if
{
//create a new Square of the given size
//call its read method to read the values of the square
System.out.println(“\n******** Square ” + count + ” ********”);
//print the square
//print the sums of its rows