Sie sind auf Seite 1von 40

Chapter 6: Arrays

Solutions
Multiple Choice
Solutions
1. c
2. d
3. b
4. c
5. b
6. e
7. c
8. a
9. d
10. c

True/False
Solutions
1. T
2. F
3. F
4. T
5. T
6. F
7. F
8. T
9. T
10. T

Short Answer Solutions


6.1.

Which of the following are valid declarations? Which instantiate an array object? Explain your answers.

int primes = {2, 3, 4, 5, 7, 11};

invalid; an int cannot be declared and initialized using an intializer list; []


is missing

float elapsedTimes[] = {11.47, 12.04, 11.72, 13.88};


valid; the [] can be placed either after the element type (float) or
after the reference variable (elapsedTimes)

int[] scores = int[30];


invalid; the right hand side of the assignment operator must contain
either an initializer list or an expression of the form, new int[30]

int[] primes = new {2,3,5,7,11};


invalid; new on the right hand side of the assignment operator is
neither necessary nor acceptable

int[] scores = new int[30];


valid; the assignment is correct Java syntax

char grades[] = {'a', 'b', 'c', 'd', 'f'};

char [] grades = new char[];

valid; the assignment is correct Java syntax

invalid; the size of the array must be indicated when the array is
instantiated. Changing the right half of the statement to "new
char[SIZE];", for example, would make the statement valid.

6.2.

Describe two programs that would be difficult to implement without using arrays.
1.)

a program to find the average midterm score of 600 students enrolled


in an introductory computer science course

2.)

a program to record and compute the sum of the snowfalls, recorded on


a daily basis for the 40 days preceding the 2006 Winter Olympics

3.)

a program to determine the relative frequency of each character in


the Cyrillic alphabet in the original version of The Brothers Karamasov

2007 Pearson Education

S 104

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

6.3.

S 105

4.)

a program to compute the mean and standard deviation of the Dow Jones
Industrial Average closings since September 11

5.)

a program to store the coordinates of the vertices of polygons


approximating the surface of a beating heart

Describe what problem occurs in the following code. What modifications should be made to it to eliminate the
problem?
int[] numbers = {3, 2, 3, 6, 9, 10, 12, 32, 3, 12, 6};
for (int count = 1; count <= numbers.length; count++)
System.out.println (numbers[count]);
The for loop fails to print the 0th element of the array, and attempts to print the
nonexistent 11th element of the array. As a consequence, an
ArrayIndexOutOfBoundsException is thrown. The problem can be eliminated by
providing a for loop which initializes count to 0 (rather than 1) and tests if
count is less than (rather than less than or equal to) numbers.length.

6.4.

Write an array declaration and any necessary supporting classes to represent the following statements:

Students names for a class of 25 students


String[] students = new String[25];

Students test grades for a class of 40 students


int[] grades = new int[40]; // for integer percentages
or
char[] grades = new char[40]; // for simple letter grades
or
String[] grades = new String[40]; /* for letter grades with
+s and -s. */

Credit-card transactions that contain a transaction number, a merchant name, and a charge

Transactions[] charges = new Transactions[number]


/* assumes int number is assigned a value prior to the array declaration */
public class Transactions
{
private int transactionNumber;
private String merchantName;
private double charge;
.
.
.
}

Students names for a class and homework grades for each student

NameAndGrades[] theClass = new NameAndGrades [enrollees]


/* assumes int enrollees is assigned a value prior to the array declaration */
public class NameAndGrades
{
private String name;
private int[] grades;
.
.
.
}

2007 Pearson Education

S 106

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

For each employee of the L&L International Corporation: the employee number, hire date, and the
amount of the last five raises

Employee[] LAndL = new Employee[staffSize]


/* assumes int staffSize is assigned a value prior to the array declaration */
public class Employee
{
private int employeeNumber;
private String hireDate;
private double raise[] = new double[5];
.
.
.
}

6.5.

Write a method called sumArray that accepts an array of floating point values and returns the sum of the
values stored in the array.
public int sumArray (int[] values)
{
int sum = 0;
for (int count = 0; count < values.length; count++)
sum += values[count];
return sum;
}

6.6.

Write a method called switchThem that accepts two integer arrays as parameters and switches the contents
of the arrays. Take into account that the arrays may be of different sizes.
public void switchThem (int[] first, int[] second)
{
if (first.length == second.length)
{
// copy contents of first into temp
int [] temp = new int[first.length];
for (int i=0; i<first.length; i++)
temp[i] = first[i];
//copy contents of second into first
for (int i=0; i<first.length; i++)
first[i] = second[i];
//copy contents of temp into second
for (int i=0; i<first.length; i++)
second[i] = temp[i];
}
else
{
System.out.println(Arrays are of different
+ sizes and cannot be switched.)
}
}

6.7.

Describe a program that would use the ArrayList class instead of arrays. Describe a program that would use
arrays instead of the ArrayList class. Explain your choices.
A program associated with a mail order Website for backpacks would use an object
of the ArrayList class to implement the choices of colors of the backpacks because
the colors and number of colors change with the seasons and as colors otherwise
gain and lose popularity. An object of the ArrayList class can grow and shrink
dynamically to accommodate these changes.
A program associated with a personal day planner, with entries possible for each
hour of the day, would use an array object to implement the choices for each hour
of the day because the number of hours in a day, and hence the number of hours for
which choices can be made for any given day, never changes. There is no need for

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

S 107

the array object to grow or shrink to accommodate a larger or smaller number of


hours.

6.8.

Write a code fragment that loops through an ArrayList<Car> using a foreach loop and prints every
element.
for (Car car : myCars)
{
System.out.println(car);
}
(where myCars is the ArrayList<Car>)

6.9.

Write a code fragment that loops through an ArrayList<Car> using a ListIterator and prints every
element.
ListIterator it = myCars.listIterator();
while (it.hasNext())
{
System.out.println(it.next());
}
(where myCars is the ArrayList<Car>)

6.10.

Explain what would happen if the radio buttons used in the QuoteOptions program were not organized into
a ButtonGroup object. Change the program to test your answer.
The three radio buttons used in the QuoteOptions program represent mutually
exclusive choices (Comedy, Philosophy, or Carpentry). Their organization into a
ButtonGroup prevents more than one of them from being selected at any point in
time.
The references comedy, philosophy, and carpentry are associated with
JRadioButtons, with comedy being set initially to true. These JRadioButtons are
added to a JPanel which is the primary panel containing the GUI. If they are not
organized into a ButtonGroup multiple buttons can be selected at one time.
However, the quote displayed is the quote associated with the last selected button
(even though other buttons also may be selected).

Programming Project Solutions


6.1 CountIntegers1
//********************************************************************
// CountIntegers1.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.1
//********************************************************************
import java.util.Scanner;
public class CountIntegers1
{
public static void main (String [] args)
{
int [] occurrences = new int [51];
Scanner scan = new Scanner (System.in);
System.out.println ("Enter integers in the range 0-50.");
System.out.print ("Signal end of list with a ");
System.out.println ("number outside the range.");
2007 Pearson Education

S 108

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

// read all the integers


int entered = scan.nextInt ();
while (entered >= 0 && entered <= 50)
{
// increment the appropriate counter
occurrences [entered] ++;
// read the next value
entered = scan.nextInt ();
}
// report all integers that were entered one or more times
//
System.out.println ("Number\tTimes");
for (int check = 0; check <= 50; check++)
if (occurrences [check] >= 1)
System.out.println (check + "\t" + occurrences [check]);
}
}
6.2 CountIntegers2
//********************************************************************
// CountIntegers2.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.2
//********************************************************************
import java.util.Scanner;
public class CountIntegers2
{
public static void main (String [] args)
{
int [] occurrences = new int [51];
Scanner scan = new Scanner (System.in);
System.out.println ("Enter integers in the range -25 to 25.");
System.out.print ("Signal end of list with a ");
System.out.println ("number outside the range.");
// read all the integers
int entered = scan.nextInt ();
while (entered >= -25 && entered <= 25)
{
// increment the appropriate counter
occurrences [entered + 25] ++;
// read the next value
entered = scan.nextInt ();
}
// report all integers that were entered one or more times
//
System.out.println ("Number\tTimes");
for (int check = -25; check <= 25; check++)
if (occurrences [check+25] >= 1)
System.out.println (check + "\t" + occurrences [check+25]);
}
}
6.3 DescendingSorts
//********************************************************************
// DescendingSorts.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.3
//
// Sorts in descending order. Demonstrates the selection sort
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

// and insertion sort algorithms.


//********************************************************************
public class DescendingSorts
{
//----------------------------------------------------------------// Sorts the specified array of integers in descending order
// using the selection sort algorithm.
//----------------------------------------------------------------public static void selectionSort (int[] numbers)
{
int min, temp;
for (int index = 0; index < numbers.length-1; index++)
{
min = index;
for (int scan = index+1; scan < numbers.length; scan++)
if (numbers[scan] > numbers[min])
min = scan;
// Swap the values
temp = numbers[min];
numbers[min] = numbers[index];
numbers[index] = temp;
}
}
//----------------------------------------------------------------// Sorts the specified array of integers in descending order
// using the insertion sort algorithm.
//----------------------------------------------------------------public static void insertionSort (int[] numbers)
{
for (int index = 1; index < numbers.length; index++)
{
int key = numbers[index];
int position = index;
// shift larger values to the right
while (position > 0 && numbers[position-1] < key)
{
numbers[position] = numbers[position-1];
position--;
}
numbers[position] = key;
}
}
}
6.3 DescendingSortsDriver
//********************************************************************
// DescendingSortsDriver.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.3
//********************************************************************
import java.util.Random;
public class DescendingSortsDriver
{
private static final int NUM = 50,
MAX = 100;
//----------------------------------------------------------------// Demonstrates the descending sorts
2007 Pearson Education

S 109

S 110

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

//----------------------------------------------------------------public static void main (String args[])


{
Random gen = new Random();
int[] numbers = new int[NUM];
Integer[] objects = new Integer[NUM];
// create random numbers
for (int i=0; i<NUM; i++)
numbers[i] = gen.nextInt(MAX) + 1;
DescendingSorts.selectionSort(numbers);
System.out.println("Selection sort of " + NUM + " random numbers in
descending order:");
for (int i=0; i<NUM; i++)
System.out.print(numbers[i] + " ");
// create new set of random numbers
for (int i=0; i<NUM; i++)
numbers[i] = gen.nextInt(MAX) + 1;
DescendingSorts.insertionSort(numbers);
System.out.println("\n\nInsertion sort of " + NUM + " random numbers in
descending order:");
for (int i=0; i<NUM; i++)
System.out.print(numbers[i] + " ");
}
}

6.4 Histogram
//********************************************************************
// Histogram.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.4
//********************************************************************
import java.util.Scanner;
public class Histogram
{
public static void main (String [] args)
{
int[] ranges = new int [10];
int box;
Scanner scan = new Scanner (System.in);
System.out.println ("Enter some numbers between 0 and 100.");
System.out.print ("Signal the end by entering ");
System.out.println ("a number out of that range.");
int entered = scan.nextInt ();
while (entered >= 1 && entered <= 100)
{
box = (entered - 1) / 10;
ranges[box] ++;
entered = scan.nextInt ();
}
// print histogram
for (box = 0; box < 10; box++)
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

{
System.out.print ((10 * box + 1) + "-");
System.out.print ((10 * box + 10) + "\t|");
for (int count = 0; count < ranges[box]; count++)
System.out.print ("*");
System.out.println ();
}
}
}
6.5 Histogram2
//********************************************************************
// Histogram2.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.5
//********************************************************************
import java.util.Scanner;
public class Histogram2
{
public static void main (String [] args)
{
int[] ranges = new int [10];
int box;
Scanner scan = new Scanner (System.in);
System.out.println ("Enter some numbers between 0 and 100.");
System.out.print ("Signal the end by entering ");
System.out.println ("a number out of that range.");
int entered = scan.nextInt ();
while (entered >= 1 && entered <= 100)
{
box = (entered - 1) / 10;
ranges[box] ++;
entered = scan.nextInt ();
}
// print histogram - a star for every 5 elements
for (box = 0; box < 10; box++)
{
System.out.print ((10 * box + 1) + "-");
System.out.print ((10 * box + 10) + "\t|");
for (int count = 5; count <= ranges[box]; count+=5)
System.out.print ("*");
System.out.println ();
}
}
}
6.6 LLBankDriver
//********************************************************************
// LLBankDriver.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.6
//********************************************************************
import java.util.Scanner;
public class LLBankDriver
{
//---------------------------------------------------------------- 2007 Pearson Education

S 111

S 112

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

// Exercises the methods of an LLBank object.


//----------------------------------------------------------------public static void main (String [] args)
{
System.out.println ("Welcome to the L & L Bank.\n");
LLBank bank = new LLBank();
bank.create();
bank.deposit();
bank.create();
bank.deposit();
bank.create();
bank.deposit();
bank.withdraw();
System.out.println ("Current Status:");
System.out.println (bank);
bank.withdraw();
bank.interest();
System.out.println ("Final Status:");
System.out.println (bank);
}
}
6.6 LLBank
//********************************************************************
// LLBank.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.6
//********************************************************************
import java.util.Scanner;
public class LLBank
{
private final int MAX = 30;
private LLBankCustomer[] customers = new LLBankCustomer[MAX];
private int count = 0;
//----------------------------------------------------------------// Sets up an initially empty bank.
//----------------------------------------------------------------public LLBank()
{
for (int idx = 0; idx < MAX; idx++)
customers[idx] = null;
}
//----------------------------------------------------------------// Create a new account.
//----------------------------------------------------------------public void create ()
{
Scanner scan = new Scanner (System.in);
System.out.println ("CREATING A NEW CUSTOMER ACCOUNT");
System.out.print ("Account number? ");
int acct = scan.nextInt ();
int index = findAccount(acct);
if (index != -1)
System.out.println ("Account number already in use.");
else
{
System.out.print ("Name of new customer? ");
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

String name = scan.nextLine ();


System.out.print ("Phone number of new customer? ");
String phone = scan.nextLine ();
customers[count] = new LLBankCustomer(acct, name, phone, 0.0);
count++;
}
}
//----------------------------------------------------------------// Prompt for deposit information, verify, and process.
//----------------------------------------------------------------public void deposit ()
{
Scanner scan = new Scanner (System.in);
System.out.println ("MAKING A DEPOSIT");
System.out.print ("Account number? ");
int acct = scan.nextInt ();
int index = findAccount(acct);
if (index == -1)
System.out.println ("Invalid account number.");
else
{
System.out.print ("Amount of deposit? ");
double amt = scan.nextDouble ();
if (amt > 0.0)
{
double update = customers[index].getBalance() + amt;
customers[index].setBalance(update);
}
else
System.out.println ("Invalid deposit amount.");
}
}
//----------------------------------------------------------------// Prompt for withdraw information, verify, and process.
//----------------------------------------------------------------public void withdraw ()
{
Scanner scan = new Scanner (System.in);
System.out.println ("MAKING A WITHDRAW");
System.out.print ("Account number? ");
int acct = scan.nextInt ();
int index = findAccount(acct);
if (index == -1)
System.out.println ("Invalid account number.");
else
{
System.out.print ("Amount of withdrawal? ");
double amt = scan.nextDouble ();
if (customers[index].getBalance() >= amt)
if (amt > 0.0)
{
double update = customers[index].getBalance() - amt;
customers[index].setBalance(update);
}
else
System.out.println ("Invalid withdrawal amount.");
else
System.out.println ("Insufficient balance.");
}
}
//----------------------------------------------------------------// Add interest to each existing accounts.
//---------------------------------------------------------------- 2007 Pearson Education

S 113

S 114

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

public void interest ()


{
System.out.println ("ADDING INTEREST");
for (int idx = 0; idx < count; idx++)
customers[idx].setBalance(customers[idx].getBalance() * 1.03);
}
//----------------------------------------------------------------// Returns the information about the bank as a string.
//----------------------------------------------------------------public String toString()
{
String result = "";
for (int idx = 0; idx < count; idx++)
{
result += customers[idx];
result += "\n";
}
return result;
}
//----------------------------------------------------------------// Searches for the specified account number. Returns -1 if not
// found.
//----------------------------------------------------------------public int findAccount (long target)
{
int result = -1, scan=0;
boolean found = false;
while (scan < count && !found)
{
if (target == customers[scan].getAccount())
{
found = true;
result = scan;
}
scan++;
}
return result;
}
}
6.6 LLBankCustomer
//********************************************************************
// LLBankCustomer.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.6
//********************************************************************
public class LLBankCustomer
{
private long account;
private String name, phone;
private double balance;
//----------------------------------------------------------------// Sets up the customer with the specified information.
//----------------------------------------------------------------public LLBankCustomer (long newAccount, String newName,
String newPhone, double newBalance)
{
account = newAccount;
name = newName;
phone = newPhone;
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

balance = newBalance;
}
//----------------------------------------------------------------// Returns the account number.
//----------------------------------------------------------------public long getAccount ()
{
return account;
}
//----------------------------------------------------------------// Sets the balance as specified.
//----------------------------------------------------------------public void setBalance (double newBalance)
{
balance = newBalance;
}
//----------------------------------------------------------------// Returns the current balance.
//----------------------------------------------------------------public double getBalance ()
{
return balance;
}
//----------------------------------------------------------------// Returns this customer's information as a string.
//----------------------------------------------------------------public String toString ()
{
return account + "\t" + name + "\t" + balance + "\t" + phone;
}
}
6.7 Grade
//********************************************************************
// Grade.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.7
//
//********************************************************************
public class Grade
{
private String grade;
private int cutoff;
//----------------------------------------------------------------// Create the grade, initializing the grade and cutoff values
//----------------------------------------------------------------public Grade(String gradeString, int cutoffValue)
{
grade = gradeString;
cutoff = cutoffValue;
}
//----------------------------------------------------------------// Return the grade string
//----------------------------------------------------------------String getGrade()
{
return grade;
}
2007 Pearson Education

S 115

S 116

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

//----------------------------------------------------------------// Return the cutoff value


//----------------------------------------------------------------int getCutoff()
{
return cutoff;
}
}
6.7GradeRange
//********************************************************************
// GradeRange.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.7
//
//********************************************************************
public class GradeRange
{
//----------------------------------------------------------------// Creates the possible grades and their numeric lowest value,
// then prints them out.
//----------------------------------------------------------------public static void main (String[] args)
{
String[] gradeString = {"A", "A-", "B+", "B", "B-", "C+", "C", "C-",
"D+", "D", "D-", "F"};
int[] cutoff = {95, 90, 87, 83, 80, 77, 73, 70, 67, 63, 60, 0};
final int NUM_GRADES = 12;
Grade[] grades = new Grade[NUM_GRADES];
for (int i=0; i<NUM_GRADES; i++) // populate array
grades[i] = new Grade (gradeString[i], cutoff[i]);
for (int level = 0; level < NUM_GRADES; level++)
System.out.println (grades[level].getGrade() + "\t" +
grades[level].getCutoff());
}
}
6.8 Card
//********************************************************************
// Card.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.8
//********************************************************************
public class Card
{
public final static
public final static
public final static
public final static
public final static
public final static
public final static
public final static
public final static
public final static
public final static
public final static
2007 Pearson Education

int
int
int
int
int
int
int
int
int
int
int
int

ACE
TWO
THREE
FOUR
FIVE
SIX
SEVEN
EIGHT
NINE
TEN
JACK
QUEEN

=
=
=
=
=
=
=
=
=
=
=
=

1; // note: or use enumerated types


2;
3;
4;
5;
6;
7;
8;
9;
10;
11;
12;

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

public final static int KING


public
public
public
public

final
final
final
final

static
static
static
static

int
int
int
int

S 117

= 13;

CLUBS
DIAMONDS
HEARTS
SPADES

=
=
=
=

1;
2;
3;
4;

private final static int NUM_FACES = 13;


private final static int NUM_SUITS = 4;
private int face, suit;
private String faceName, suitName;
//----------------------------------------------------------------// Creates a random card.
//----------------------------------------------------------------public Card ()
{
face = (int) (Math.random() * NUM_FACES) + 1;
setFaceName();
suit = (int) (Math.random() * NUM_SUITS) + 1;
setSuitName();
}
//----------------------------------------------------------------// Creates a card of the specified suit and face value.
//----------------------------------------------------------------public Card (int faceValue, int suitValue)
{
face = faceValue;
setFaceName();
suit = suitValue;
setSuitName();
}
//----------------------------------------------------------------// Sets the string representation of the face using its stored
// numeric value.
//----------------------------------------------------------------private void setFaceName()
{
switch (face)
{
case ACE:
faceName = "Ace";
break;
case TWO:
faceName = "Two";
break;
case THREE:
faceName = "Three";
break;
case FOUR:
faceName = "Four";
break;
case FIVE:
faceName = "Five";
break;
case SIX:
faceName = "Six";
break;
case SEVEN:
faceName = "Seven";
break;
2007 Pearson Education

S 118

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

case EIGHT:
faceName
break;
case NINE:
faceName
break;
case TEN:
faceName
break;
case JACK:
faceName
break;
case QUEEN:
faceName
break;
case KING:
faceName
break;

= "Eight";
= "Nine";
= "Ten";
= "Jack";
= "Queen";
= "King";

}
}
//----------------------------------------------------------------// Sets the string representation of the suit using its stored
// numeric value.
//----------------------------------------------------------------private void setSuitName()
{
switch (suit)
{
case CLUBS:
suitName = "Clubs";
break;
case DIAMONDS:
suitName = "Diamonds";
break;
case HEARTS:
suitName = "Hearts";
break;
case SPADES:
suitName = "Spades";
break;
}
}
//----------------------------------------------------------------// Determines if this card is higher than the passed card. The
// second parameter determines if aces should be considered high
// (beats a King) or low (lowest of all faces). Uses the suit
// if both cards have the same face.
//----------------------------------------------------------------public boolean isHigherThan (Card card2, boolean aceHigh)
{
boolean result = false;
if (face == card2.getFace())
{
if (suit > card2.getSuit())
result = true;
}
else
{
if (aceHigh && face == ACE)
result = true;
else
if (face > card2.getFace())
result = true;
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

}
return result;
}
//----------------------------------------------------------------// Determines if this card is higher than the passed card,
// assuming that aces should be considered high.
//----------------------------------------------------------------public boolean isHigherThan (Card card2)
{
return isHigherThan (card2, true);
}
//----------------------------------------------------------------// Returns the face (numeric value) of this card.
//----------------------------------------------------------------public int getFace ()
{
return face;
}
//----------------------------------------------------------------// Returns the suit (numeric value) of this card.
//----------------------------------------------------------------public int getSuit ()
{
return suit;
}
//----------------------------------------------------------------// Returns the face (string value) of this card.
//----------------------------------------------------------------public String getFaceName ()
{
return faceName;
}
//----------------------------------------------------------------// Returns the suit (string value) of this card.
//----------------------------------------------------------------public String getSuitName ()
{
return suitName;
}
//----------------------------------------------------------------// Returns the string representation of this card, including
// both face and suit.
//----------------------------------------------------------------public String toString ()
{
return faceName + " of " + suitName;
}
}
6.8 Deck
//********************************************************************
// Deck.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.8
//********************************************************************
import java.util.Random;
public class Deck
2007 Pearson Education

S 119

S 120

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

{
private int numCards;
private Card[] cards;
private int NUM_CARDS = 52;
//----------------------------------------------------------------// Creates a deck, cards are created in order
//----------------------------------------------------------------public Deck()
{
numCards = NUM_CARDS;
cards = new Card[numCards];
//create the deck (cards created in order)
int cardIndex = 0;
for (int face = Card.ACE; face <= Card.KING; face++)
for (int suit = Card.CLUBS; suit <= Card.SPADES; suit++)
cards[cardIndex++] = new Card(face, suit);
}
//----------------------------------------------------------------// Deals a card from the deck
//----------------------------------------------------------------public Card deal()
{
if (numCards > 0)
return cards[--numCards];
else
return null;
}
//----------------------------------------------------------------// Returns the number of cards left in the deck
//----------------------------------------------------------------public int getNumCardsInDeck()
{
return numCards;
}
//----------------------------------------------------------------// Returns true is the deck has cards in it, else false
//----------------------------------------------------------------public boolean hasMoreCards()
{
return (numCards > 0);
}
//----------------------------------------------------------------// Shuffles the deck. Resets the number of cards in the deck to 52
//----------------------------------------------------------------public void shuffle()
{
Random gen = new Random();
numCards = NUM_CARDS;
boolean[] taken= new boolean[NUM_CARDS];
for (int i=0; i<numCards; i++)
taken[i] = false;
int[] shufflePositions = new int[NUM_CARDS];
int count = 0;
// determine shuffled positions
while (count < 52)
{
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

int place = gen.nextInt(NUM_CARDS);


if (!taken[place])
{
shufflePositions[count] = place;
taken[place] = true;
count++;
}
}
// move cards to shuffled positions
Card[] temp = new Card[NUM_CARDS];
for (int i=0; i< numCards; i++)
temp[shufflePositions[i]] = cards[i];
cards = temp;
}
}
6.8 CardDriver
//********************************************************************
// CardDriver.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.8
//********************************************************************
public class CardDriver
{
//----------------------------------------------------------------// Creates a deck, shuffles the deck and deals the cards.
//----------------------------------------------------------------public static void main (String args[])
{
Deck deck = new Deck();
deck.shuffle();
int cardNumber = 0;
System.out.println("Dealing shuffled cards:");
while (deck.hasMoreCards())
System.out.println("
" + ++cardNumber + ": " + deck.deal());
}
}
6.9 Complexity
//********************************************************************
// Complexity.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.9 & 6.10
//
// Represents the interface for an object that can be assigned an
// explicit complexity.
//********************************************************************
public interface Complexity
{
public void setComplexity (int complexity);
public int getComplexity();
}
6.9 Question
//********************************************************************
// Question.java
Author: Lewis/Loftus/Cocking
2007 Pearson Education

S 121

S 122

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

//
// Solution to Programming Project 6.9 & 6.10
//
//********************************************************************
public class Question implements Complexity
{
private String question, answer;
private int complexityLevel;
//----------------------------------------------------------------// Sets up the question with a default complexity.
//----------------------------------------------------------------public Question (String query, String result)
{
question = query;
answer = result;
complexityLevel = 1;
}
//----------------------------------------------------------------// Sets the complexity level for this question.
//----------------------------------------------------------------public void setComplexity (int level)
{
complexityLevel = level;
}
//----------------------------------------------------------------// Returns the complexity level for this question.
//----------------------------------------------------------------public int getComplexity()
{
return complexityLevel;
}
//----------------------------------------------------------------// Returns the question.
//----------------------------------------------------------------public String getQuestion()
{
return question;
}
//----------------------------------------------------------------// Returns the answer to this question.
//----------------------------------------------------------------public String getAnswer()
{
return answer;
}
//----------------------------------------------------------------// Returns true if the candidate answer matches the answer.
//----------------------------------------------------------------public boolean answerCorrect (String candidateAnswer)
{
return answer.equals(candidateAnswer);
}
//----------------------------------------------------------------// Returns this question (and its answer) as a string.
//----------------------------------------------------------------public String toString()
{
return question + "\n" + answer;
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

}
}
6.9 Quiz
//********************************************************************
// Quiz.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.9
//
//********************************************************************
import java.util.Scanner;
public class Quiz
{
private final int MAX_QUESTIONS = 25;
private Question[] questions;
private int current;
private int correct;
private int incorrect;
public Quiz()
{
questions = new Question[MAX_QUESTIONS];
current = 0;
correct = incorrect = 0;
}
public void add(Question newQuestion)
{
if (current < MAX_QUESTIONS)
questions[current++] = newQuestion;
}
public void giveQuiz()
{
Scanner scan = new Scanner (System.in);
for (int i = 0; i < current; i++)
{
System.out.println(questions[i].getQuestion());
if (questions[i].answerCorrect(scan.nextLine()))
correct++;
else
correct--;
}
}
public int getNumCorrect()
{
return correct;
}
public int getNumIncorrect()
{
return incorrect;
}
}
6.9 QuizTime
//********************************************************************
// QuizTime.java
Author: Lewis/Loftus/Cocking
//
2007 Pearson Education

S 123

S 124

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

// Solution to Programming Project 6.9


//
//********************************************************************
public class QuizTime
{
public static void main(String[] args)
{
Quiz q = new Quiz();
q.add(new Question ("What is the wind speed flight velocity of a
swallow?",
"African or European?"));
q.add(new Question ("What color was George Washington's white horse?",
"white"));
q.add(new Question ("How much wood could a woodchuck chuck?",
"Wouldn't know"));
q.add(new Question ("What's my favorite programming language?",
"Java"));
q.add(new Question ("What is the capital of Bolivia?",
"La Paz"));
q.add(new Question ("How many moons does the planet Venus have?",
"zero"));
q.giveQuiz();
System.out.print("\nResults:\n\tCorrect: " + q.getNumCorrect());
System.out.println("\tIncorrect: " + q.getNumIncorrect());
}
}
6.10 Complexity
//********************************************************************
// Complexity.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.9 & 6.10
//
// Represents the interface for an object that can be assigned an
// explicit complexity.
//********************************************************************
public interface Complexity
{
public void setComplexity (int complexity);
public int getComplexity();
}
6.10 Question
//********************************************************************
// Question.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.9 & 6.10
//
//********************************************************************
public class Question implements Complexity
{
private String question, answer;
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

private int complexityLevel;


//----------------------------------------------------------------// Sets up the question with a default complexity.
//----------------------------------------------------------------public Question (String query, String result)
{
question = query;
answer = result;
complexityLevel = 1;
}
//----------------------------------------------------------------// Sets the complexity level for this question.
//----------------------------------------------------------------public void setComplexity (int level)
{
complexityLevel = level;
}
//----------------------------------------------------------------// Returns the complexity level for this question.
//----------------------------------------------------------------public int getComplexity()
{
return complexityLevel;
}
//----------------------------------------------------------------// Returns the question.
//----------------------------------------------------------------public String getQuestion()
{
return question;
}
//----------------------------------------------------------------// Returns the answer to this question.
//----------------------------------------------------------------public String getAnswer()
{
return answer;
}
//----------------------------------------------------------------// Returns true if the candidate answer matches the answer.
//----------------------------------------------------------------public boolean answerCorrect (String candidateAnswer)
{
return answer.equals(candidateAnswer);
}
//----------------------------------------------------------------// Returns this question (and its answer) as a string.
//----------------------------------------------------------------public String toString()
{
return question + "\n" + answer;
}
}
6.10 Quiz2
//********************************************************************
// Quiz2.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.10
2007 Pearson Education

S 125

S 126

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

//
//********************************************************************
import java.util.Scanner;
public class Quiz2
{
private final int MAX_QUESTIONS = 25;
private Question[] questions;
private int current;
private int correct;
private int incorrect;
public Quiz2()
{
questions = new Question[MAX_QUESTIONS];
current = 0;
correct = incorrect = 0;
}
public void add(Question newQuestion)
{
if (current < MAX_QUESTIONS)
questions[current++] = newQuestion;
}
public void giveQuiz()
{
Scanner scan = new Scanner (System.in);
for (int i = 0; i < current; i++)
{
System.out.println(questions[i].getQuestion());
if (questions[i].answerCorrect(scan.nextLine()))
correct++;
else
correct--;
}
}
public void giveQuiz(int minComplexity, int maxComplexity)
{
Scanner scan = new Scanner (System.in);
for (int i = 0; i < current; i++)
{
int complexity = questions[i].getComplexity();
if (complexity >= minComplexity && complexity <= maxComplexity)
{
System.out.println(questions[i].getQuestion());
if (questions[i].answerCorrect(scan.nextLine()))
correct++;
else
correct--;
}
}
if (correct == 0 && incorrect == 0)
System.out.println("Sorry, no questions fall within the specified
complexity range");
}
public int getNumCorrect()
{
return correct;
}
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

S 127

public int getNumIncorrect()


{
return incorrect;
}
}
6.10 QuizTime2
//********************************************************************
// QuizTime2.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.10
//
//********************************************************************
public class QuizTime2
{
public static void main(String[] args)
{
Quiz2 q = new Quiz2();
Question temp;
temp = new Question ("What is the wind speed flight velocity of a
swallow?",
"African or European?");
temp.setComplexity(2);
q.add(temp);
temp = new Question ("What color was George Washington's white horse?",
"white");
temp.setComplexity(1);
q.add(temp);
temp = new Question ("How much wood could a woodchuck chuck?",
"Wouldn't know");
temp.setComplexity(2);
q.add(temp);
temp = new Question ("What's my favorite programming language?",
"Java");
temp.setComplexity(1);
q.add(temp);
temp = new Question ("What is the capital of Bolivia?",
"La Paz");
temp.setComplexity(4);
q.add(temp);
temp = new Question ("How many moons does the planet Venus have?",
"zero");
temp.setComplexity(4);
q.add(temp);
temp = new Question ("Outside of the USA, what is the largest software
producing country?",
"Ireland");
temp.setComplexity(4);
q.add(temp);
temp = new Question ("What country is Mt. Everest located in?",
"Nepal");
temp.setComplexity(3);
q.add(temp);
2007 Pearson Education

S 128

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

q.giveQuiz(3,5);
System.out.print("\nResults:\n\tCorrect: " + q.getNumCorrect());
System.out.println("\tIncorrect: " + q.getNumIncorrect());
}
}
6.11 SortedTunes
//********************************************************************
// SortedTunes.java
Author: Lewis/Loftus/Cocking
//
// Solution for Programming Project 6.11
//********************************************************************
public class SortedTunes
{
//----------------------------------------------------------------// Creates a CDCollection object and adds some CDs to it. Prints
// reports on the status of the sorted collection.
//----------------------------------------------------------------public static void main (String[] args)
{
SortedCDCollection music = new SortedCDCollection();
music.addCD
music.addCD
music.addCD
music.addCD
music.addCD
music.addCD

("Storm Front", "Joel, Billy", 14.95, 10);


("Come On Over", "Twain, Shania", 14.95, 16);
("Les Miserables", "Hugo, Victor", 17.95, 33);
("Graceland", "Simon, Paul", 13.90, 11);
("The Stranger", "Joel, Billy", 14.95, 12);
("How Do You Like Me Now", "Keith, Toby", 15.49, 26);

System.out.println (music);
music.addCD
music.addCD
music.addCD
music.addCD
music.addCD
music.addCD

("Greatest Hits", "Buffet, Jimmy", 15.95, 13);


("Breathe", "Hill, Faith", 16.45, 13);
("Place In The Sun", "McGraw, Tim", 19.99, 26);
("52nd Street", "Joel, Billy", 14.95, 11);
("Double Live", "Brooks, Garth", 19.99, 26);
("Fly", "Dixie Chicks", 14.99, 26);

System.out.println (music);
}
}
6.11 SortedCDCollection
//********************************************************************
// SortedCDCollection.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.11
//********************************************************************
import java.text.NumberFormat;
public class SortedCDCollection
{
private SortableCD[] collection;
private int count;
private double totalValue;
private int currentSize;
//----------------------------------------------------------------// Creates an initially empty collection.
//----------------------------------------------------------------public SortedCDCollection ()
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

{
currentSize = 100;
collection = new SortableCD[currentSize];
count = 0;
totalValue = 0.0;
}
//----------------------------------------------------------------// Adds a CD to the collection, increasing the size of the
// collection if necessary.
//----------------------------------------------------------------public void addCD (String title, String artist, double value,
int tracks)
{
if (count == currentSize)
increaseSize();
collection[count] = new SortableCD(title, artist, value, tracks);
count++;
totalValue += value;
}
//----------------------------------------------------------------// Returns a report describing the CD collection, sorting first.
//----------------------------------------------------------------public String toString()
{
sortCDs ();
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String report = "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n";
report += "My CD Collection\n\n";
report += "Number of CDs: " + count + "\n";
report += "Total value: " + fmt.format(totalValue) + "\n";
report += "Average cost: " + fmt.format(totalValue/count);
report += "\n\nCD List:\n\n";
for (int cd = 0; cd < count; cd++)
report += collection[cd].toString() + "\n";
return report;
}
//----------------------------------------------------------------// Doubles the size of the collection by creating a larger array
// and copying into it the existing collection.
//----------------------------------------------------------------private void increaseSize ()
{
currentSize *= 2;
SortableCD[] temp = new SortableCD[currentSize];
for (int cd = 0; cd < collection.length; cd++)
temp[cd] = collection[cd];
collection = temp;
}
//----------------------------------------------------------------// Copy SortableCD array into a temporary array of the exact
2007 Pearson Education

S 129

S 130

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

// size, sorts them, then copies them back.


//----------------------------------------------------------------private void sortCDs()
{
SortableCD[] temp = new SortableCD[count];
for (int copy = 0; copy < count; copy++)
temp [copy] = collection [copy];
Sorts.insertionSort (temp);
for (int copy = 0; copy < count; copy++)
collection[copy] = temp[copy];
}
}
6.11 SortableCD
//********************************************************************
// SortableCD.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.11
//********************************************************************
import java.text.NumberFormat;
public class SortableCD implements Comparable
{
private String title, artist;
private double value;
private int tracks;
//----------------------------------------------------------------// Creates a new SortableCD with the specified information.
//----------------------------------------------------------------public SortableCD (String theTitle, String theArtist,
double theValue, int theTracks)
{
title = theTitle;
artist = theArtist;
value = theValue;
tracks = theTracks;
}
//----------------------------------------------------------------// Returns a description of this SortableCD.
//----------------------------------------------------------------public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String description;
description = fmt.format(value) + "\t" + tracks + "\t";
description += artist + "\t" + title;
return description;
}
//----------------------------------------------------------------// Determines the relationship to another SortableCD, satisfying
// the Comparable interface. Sorts first by artist name, then
// by title.
//----------------------------------------------------------------public int compareTo (Object obj)
{
SortableCD other = (SortableCD) obj;
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

int result = artist.compareTo (other.getArtist());


if (result == 0)
result = title.compareTo (other.getTitle());
return result;
}
//----------------------------------------------------------------// Returns the artist name for this SortableCD.
//----------------------------------------------------------------public String getArtist()
{
return artist;
}
//----------------------------------------------------------------// Returns the title of this SortableCD.
//----------------------------------------------------------------public String getTitle()
{
return title;
}
}
6.11 Sorts
//********************************************************************
// Sorts.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.11
//
// Demonstrates the selection sort and insertion sort algorithms,
// as well as a generic object sort.
//********************************************************************
public class Sorts
{
//----------------------------------------------------------------// Sorts the specified array of integers using the selection
// sort algorithm.
//----------------------------------------------------------------public static void selectionSort (int[] numbers)
{
int min, temp;
for (int index = 0; index < numbers.length-1; index++)
{
min = index;
for (int scan = index+1; scan < numbers.length; scan++)
if (numbers[scan] < numbers[min])
min = scan;
// Swap the values
temp = numbers[min];
numbers[min] = numbers[index];
numbers[index] = temp;
}
}
//----------------------------------------------------------------// Sorts the specified array of integers using the insertion
// sort algorithm.
//----------------------------------------------------------------public static void insertionSort (int[] numbers)
{
for (int index = 1; index < numbers.length; index++)
{
2007 Pearson Education

S 131

S 132

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

int key = numbers[index];


int position = index;
// shift larger values to the right
while (position > 0 && numbers[position-1] > key)
{
numbers[position] = numbers[position-1];
position--;
}
numbers[position] = key;
}
}
//----------------------------------------------------------------// Sorts the specified array of objects using the insertion
// sort algorithm.
//----------------------------------------------------------------public static void insertionSort (Comparable[] objects)
{
for (int index = 1; index < objects.length; index++)
{
Comparable key = objects[index];
int position = index;
// shift larger values to the right
while (position > 0 && objects[position-1].compareTo(key) > 0)
{
objects[position] = objects[position-1];
position--;
}
objects[position] = key;
}
}
}
6.12 Contact
//********************************************************************
// Contact.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.12
//
// Represents a phone contact.
//********************************************************************
public class Contact implements Comparable
{
private String firstName, lastName, phone;
//----------------------------------------------------------------// Sets up this contact with the specified information.
//----------------------------------------------------------------public Contact (String first, String last, String telephone)
{
firstName = first;
lastName = last;
phone = telephone;
}
//----------------------------------------------------------------// Returns a description of this contact as a string.
//----------------------------------------------------------------public String toString ()
{
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

return lastName + ", " + firstName + "\t" + phone;


}
//----------------------------------------------------------------// Uses both last and first names to determine lexical ordering.
//----------------------------------------------------------------public int compareTo (Object other)
{
int result;
if (lastName.equals(((Contact)other).lastName))
result = firstName.compareTo(((Contact)other).firstName);
else
result = lastName.compareTo(((Contact)other).lastName);
return result;
}
}
6.12 ObjectSort
//********************************************************************
// ObjectSort.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.12
//
// Demonstrates the selection sort and insertion sort algorithms
// based on generic objects.
//********************************************************************
public class ObjectSort
{
//----------------------------------------------------------------// Sorts the specified array of objects using the selection
// sort algorithm.
//----------------------------------------------------------------public static void selectionSort (Comparable[] objects)
{
int min;
Comparable temp;
for (int index = 0; index < objects.length-1; index++)
{
min = index;
for (int scan = index+1; scan < objects.length; scan++)
if (objects[scan].compareTo(objects[min]) < 0)
min = scan;
// Swap the values
temp = objects[min];
objects[min] = objects[index];
objects[index] = temp;
}
}
//----------------------------------------------------------------// Sorts the specified array of objects using the insertion
// sort algorithm.
//----------------------------------------------------------------public static void insertionSort (Comparable[] objects)
{
for (int index = 1; index < objects.length; index++)
{
Comparable key = objects[index];
int position = index;
// shift larger values to the right
while (position > 0 && objects[position-1].compareTo(key) > 0)
2007 Pearson Education

S 133

S 134

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

{
objects[position] = objects[position-1];
position--;
}
objects[position] = key;
}
}
}
6.12 SortPhoneList
//********************************************************************
// SortPhoneList.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.12
//
// Driver for testing an object sort.
//********************************************************************
public class SortPhoneList
{
//----------------------------------------------------------------// Creates an array of Contact objects, sorts them, then prints
// them.
//----------------------------------------------------------------public static void main (String[] args)
{
Contact[] friends = new Contact[7];
friends[0]
friends[1]
friends[2]
friends[3]
friends[4]
friends[5]
friends[6]

=
=
=
=
=
=
=

new
new
new
new
new
new
new

Contact
Contact
Contact
Contact
Contact
Contact
Contact

("John", "Smith", "610-555-7384");


("Sarah", "Barnes", "215-555-3827");
("Mark", "Riley", "733-555-2969");
("Laura", "Getz", "663-555-3984");
("Larry", "Smith", "464-555-3489");
("Frank", "Phelps", "322-555-2284");
("Marsha", "Grant", "243-555-2837");

ObjectSort.selectionSort(friends);
for (int index = 0; index < friends.length; index++)
System.out.println (friends[index]);
}
}
6.13 SteppedSort
//********************************************************************
// SteppedSort.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.13
//
// Performs a selection sort one step at a time.
//********************************************************************
import java.awt.*;
public class SteppedSort
{
private int[] numbers;
private int index;
//----------------------------------------------------------------// Creates a new sort object to sort the values in the parameter
// unsortedArray
//---------------------------------------------------------------- 2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

public SteppedSort(int[] unsortedArray)


{
numbers = unsortedArray;
index = 0;
}
//----------------------------------------------------------------// Performs one step of the selection sort algorithm.
//----------------------------------------------------------------public void nextStep ()
{
int min, temp;
if (index < numbers.length-1)
{
min = index;
for (int scan = index+1; scan < numbers.length; scan++)
if (numbers[scan] < numbers[min])
min = scan;
// Swap the values
temp = numbers[min];
numbers[min] = numbers[index];
numbers[index] = temp;
index++;
}
}
//----------------------------------------------------------------// Returns true if all integers in array are sorted
//----------------------------------------------------------------public boolean sortFinished()
{
return (index >= numbers.length-1);
}
//----------------------------------------------------------------// Draws a graphical representation of the sort.
//----------------------------------------------------------------public void draw(Graphics page, int width, int height)
{
if (sortFinished())
page.drawString("Finished Sort", 10, height - 10);
int step = width / (numbers.length + 1);
for (int i=0; i<numbers.length; i++)
{
page.setColor(Color.blue);
page.drawLine((i+1)*step, 0, (i+1)*step, numbers[i]);
}
}
}
6.13 SortAnimation
//********************************************************************
// SortAnimation.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.13
//
//********************************************************************
import javax.swing.JApplet;
public class SortAnimation extends JApplet
{
2007 Pearson Education

S 135

S 136

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

public void init()


{
getContentPane().add(new SortAnimationPanel());
}
}
6.13 SortAnimationPanel
//********************************************************************
// SortAnimationPanel.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.13
//
//********************************************************************
import
import
import
import

javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.Random;

public class SortAnimationPanel extends JPanel


{
private Timer timer;
private SteppedSort sortEngine;
private final int DELAY = 200,
NUM = 50,
MAX = 85;
public SortAnimationPanel()
{
int[] numbers = new int[NUM];
Random gen = new Random();
for (int i=0; i<NUM; i++)
numbers[i] = gen.nextInt(MAX) + 16;
sortEngine = new SteppedSort(numbers);
timer = new Timer(DELAY, null);
timer.addActionListener(new ReboundListener());
timer.start();
setBackground(Color.white);
}
public void paintComponent(Graphics page)
{
super.paintComponent(page);
sortEngine.draw(page, getWidth(), getHeight());
}
//*****************************************************************
// Represents the action listener for the timer.
//*****************************************************************
private class ReboundListener implements ActionListener
{
//-------------------------------------------------------------// Performs one step in the sort and updates the display
//-------------------------------------------------------------public void actionPerformed (ActionEvent event)
{
if (!sortEngine.sortFinished())
{
sortEngine.nextStep();
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

repaint();
}
}
}
}
6.14 SteppedInsertionSort
//********************************************************************
// SteppedInsertionSort.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.14
//
// Performs an insertion sort one step at a time.
//********************************************************************
import java.awt.*;
public class SteppedInsertionSort
{
private int[] numbers;
private int index;
//----------------------------------------------------------------// Creates a new sort object to sort the values in the parameter
// unsortedArray
//----------------------------------------------------------------public SteppedInsertionSort(int[] unsortedArray)
{
numbers = unsortedArray;
index = 1;
}
//----------------------------------------------------------------// Performs one step of the insertion sort algorithm.
//----------------------------------------------------------------public void nextStep ()
{
int key = numbers[index];
int position = index;
// shift larger values to the right
while (position > 0 && numbers[position-1] > key)
{
numbers[position] = numbers[position-1];
position--;
}
numbers[position] = key;
index++;
}
//----------------------------------------------------------------// Returns true if all integers in array are sorted
//----------------------------------------------------------------public boolean sortFinished()
{
return (index >= numbers.length);
}
//----------------------------------------------------------------// Draws a graphical representation of the sort.
//----------------------------------------------------------------public void draw(Graphics page, int width, int height)
{
2007 Pearson Education

S 137

S 138

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

if (sortFinished())
page.drawString("Finished Sort", 10, height - 10);
int step = width / (numbers.length + 1);
for (int i=0; i<numbers.length; i++)
{
page.setColor(Color.blue);
page.drawLine((i+1)*step, 0, (i+1)*step, numbers[i]);
}
}
}
6.14 Sort2Animation
//********************************************************************
// SortAnimation.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.14
//
//********************************************************************
import javax.swing.JApplet;
public class Sort2Animation extends JApplet
{
public void init()
{
getContentPane().add(new Sort2AnimationPanel());
}
}
6.14 Sort2AnimationPanel
//********************************************************************
// Sort2AnimationPanel.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.14
//
//********************************************************************
import
import
import
import

javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.Random;

public class Sort2AnimationPanel extends JPanel


{
private Timer timer;
private SteppedInsertionSort sortEngine;
private final int DELAY = 200,
NUM = 50,
MAX = 85;
public Sort2AnimationPanel()
{
int[] numbers = new int[NUM];
Random gen = new Random();
for (int i=0; i<NUM; i++)
numbers[i] = gen.nextInt(MAX) + 16;
sortEngine = new SteppedInsertionSort(numbers);
timer = new Timer(DELAY, null);
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

timer.addActionListener(new ReboundListener());
timer.start();
setBackground(Color.white);
}
public void paintComponent(Graphics page)
{
super.paintComponent(page);
sortEngine.draw(page, getWidth(), getHeight());
}
//*****************************************************************
// Represents the action listener for the timer.
//*****************************************************************
private class ReboundListener implements ActionListener
{
//-------------------------------------------------------------// Performs one step in the sort and updates the display
//-------------------------------------------------------------public void actionPerformed (ActionEvent event)
{
if (!sortEngine.sortFinished())
{
sortEngine.nextStep();
repaint();
}
}
}
}
6.15 DrawStars
//********************************************************************
// DrawStars.java
Author: Lewis/ Loftus/Cocking
//
// Solution to Programming Project 6.15
//********************************************************************
import
import
import
import
import

javax.swing.JApplet;
java.awt.Color;
java.awt.Point;
java.awt.Graphics;
java.util.Random;

public class DrawStars extends JApplet


{
private final int APPLET_WIDTH = 200;
private final int APPLET_HEIGHT = 200;
private Random gen = new Random ();
//----------------------------------------------------------------// Draws several stars of random size and color in random
// locations.
//----------------------------------------------------------------public void paint (Graphics page)
{
setBackground (Color.black);
Star star;
int radius, red, green, blue, xCenter, yCenter;
Color color;
Point center;
for (int count = 1; count <= 10; count++)
2007 Pearson Education

S 139

S 140

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

{
radius = gen.nextInt(10) + 10;
red = gen.nextInt (156) + 100;
green = gen.nextInt (156) + 100;
blue = gen.nextInt (156) + 100;
color = new Color (red, green, blue);
xCenter = gen.nextInt (180) + 10;
yCenter = gen.nextInt (180) + 10;
center = new Point (xCenter, yCenter);
star = new Star (radius, color);
star.draw (center, page);
}
}
}
6.15 Star
//********************************************************************
// Star.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.15
//********************************************************************
import java.awt.Color;
import java.awt.Point;
import java.awt.Graphics;
public class Star
{
private int radius = 10;
private Color color = Color.yellow;
//----------------------------------------------------------------// Sets up the star with a specified radius and color.
//----------------------------------------------------------------public Star (int r, Color c)
{
radius = r;
color = c;
}
//----------------------------------------------------------------// Draw the star on the specified Graphics object
//----------------------------------------------------------------public void draw (Point center, Graphics page)
{
int[] x = new int [12];
int[] y = new int [12];
int oneThird = radius/3;
int half = radius/2;
int twoThirds = radius*2/3;
int centerX = center.x;
int centerY = center.y;
x[0]
x[1]
x[2]
x[3]
x[4]
x[5]
x[6]
x[7]

=
=
=
=
=
=
=
=

centerX;
centerX +
centerX +
centerX +
centerX +
centerX +
centerX;
centerX -

2007 Pearson Education

oneThird;
twoThirds;
half;
twoThirds;
oneThird;
oneThird;

y[0]
y[1]
y[2]
y[3]
y[4]
y[5]
y[6]
y[7]

=
=
=
=
=
=
=
=

centerY centerY centerY centerY;


centerY +
centerY +
centerY +
centerY +

radius;
oneThird;
twoThirds;
twoThirds;
oneThird;
radius;
oneThird;

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

x[8] = centerX - twoThirds;


x[9] = centerX - half;
x[10] = centerX - twoThirds;
x[11] = centerX - oneThird;

S 141

y[8] = centerY + twoThirds;


y[9] = centerY;
y[10] = centerY - twoThirds;
y[11] = centerY - oneThird;

page.setColor (color);
page.fillPolygon (x, y, x.length);
}
}
6.16 Checkers
//********************************************************************
// Checkers.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 6.16
//********************************************************************
import
import
import
import

javax.swing.JApplet;
java.awt.Graphics;
java.awt.Color;
java.util.Random;

public class Checkers extends JApplet


{
int[][] checkerBoard;
private int NUM_ROWS = 8,
NUM_RED = 5,
NUM_BLACK = 8,
BLACK = -1,
EMPTY = 0,
RED_CHECKER = 1,
BLACK_CHECKER = 2,
INSET = 5;
//----------------------------------------------------------------// Creates a checkboard and adds checker in random positions
//----------------------------------------------------------------public void init()
{
checkerBoard = new int[NUM_ROWS][NUM_ROWS];
int j;
for (int i=0; i<NUM_ROWS; i++)
for (j=0; j<NUM_ROWS; j++)
if ((i % 2 == 0) == (j % 2 == 0))
checkerBoard[i][j] = BLACK;
else
checkerBoard[i][j] = EMPTY;
populateBoard();
}
//----------------------------------------------------------------// Generates random checkers
//----------------------------------------------------------------public void populateBoard()
{
Random gen = new Random();
int number = 0;
// create red checkers
while (number < NUM_RED)
{
int x = gen.nextInt(NUM_ROWS);
int y = gen.nextInt(NUM_ROWS);
if (checkerBoard[x][y] == EMPTY)
{
2007 Pearson Education

S 142

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

checkerBoard[x][y] = RED_CHECKER;
number++;
}
}
// create black checkers
number = 0;
while (number < NUM_BLACK)
{
int x = gen.nextInt(NUM_ROWS);
int y = gen.nextInt(NUM_ROWS);
if (checkerBoard[x][y] == EMPTY)
{
checkerBoard[x][y] = BLACK_CHECKER;
number++;
}
}
}
//----------------------------------------------------------------// Draws the checkerboard
//----------------------------------------------------------------public void paint(Graphics page)
{
int size;
if (getWidth() < getHeight())
size = getHeight();
else
size = getWidth();
size = size / NUM_ROWS;
int j;
for (int i=0; i<NUM_ROWS; i++)
for (j=0; j<NUM_ROWS; j++)
{
if (checkerBoard[i][j] == BLACK)
{
page.setColor(Color.darkGray);
page.fillRect(j*size, i*size, size, size);
}
else
{
page.setColor(Color.red);
page.fillRect(j*size, i*size, size, size);
page.setColor(Color.black);
if (checkerBoard[i][j] == RED_CHECKER)
page.drawOval(j*size + INSET, i*size + INSET,
size - INSET*2, size - INSET*2);
if (checkerBoard[i][j] == BLACK_CHECKER)
page.fillOval(j*size + INSET, i*size + INSET,
size - INSET*2, size - INSET*2);
}
}
}
}

AP-Style Multiple Choice


Solutions
1. E
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 6 Solutions

2.
3.
4.
5.
6.

A
C
D
C
B

AP-Style Free Response Solution


6.1
a.
public Student getValedictorian ()
{
double bestGPA = 0;
Student valedictorian = null;
for (Student student : students)
{
if (student.getGPA() > bestGPA)
{
bestGPA = student.getGPA();
valedictorian = student;
}
}
return valedictorian;
}

b.
public double getHonorsPercent ()
{
int numHonors = 0;
for (Student student : students)
{
if (student.isHonors())
{
numHonors++;
}
}
return (double)numHonors / students.length;
}

c.
private ArrayList<Student> students;

2007 Pearson Education

S 143

Das könnte Ihnen auch gefallen