Chapter 6: Arrays: Solutions
Chapter 6: Arrays: Solutions
Chapter 6: Arrays: Solutions
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
Which of the following are valid declarations? Which instantiate an array object? Explain your answers.
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.)
2.)
3.)
S 104
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.)
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:
Credit-card transactions that contain a transaction number, a merchant name, and a charge
Students names for a class and homework grades for each student
S 106
For each employee of the L&L International Corporation: the employee number, hire date, and the
amount of the last five raises
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
S 107
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).
S 108
S 109
S 110
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
{
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
S 113
S 114
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
int
int
int
int
int
int
int
int
int
int
int
int
ACE
TWO
THREE
FOUR
FIVE
SIX
SEVEN
EIGHT
NINE
TEN
JACK
QUEEN
=
=
=
=
=
=
=
=
=
=
=
=
final
final
final
final
static
static
static
static
int
int
int
int
S 117
= 13;
CLUBS
DIAMONDS
HEARTS
SPADES
=
=
=
=
1;
2;
3;
4;
S 118
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
}
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
{
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
S 121
S 122
//
// 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
}
}
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
S 125
S 126
//
//********************************************************************
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
S 127
S 128
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
System.out.println (music);
music.addCD
music.addCD
music.addCD
music.addCD
music.addCD
music.addCD
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
{
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
S 131
S 132
S 133
S 134
{
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
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
S 135
S 136
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.Random;
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
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;
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;
S 139
S 140
{
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 -
oneThird;
twoThirds;
half;
twoThirds;
oneThird;
oneThird;
y[0]
y[1]
y[2]
y[3]
y[4]
y[5]
y[6]
y[7]
=
=
=
=
=
=
=
=
radius;
oneThird;
twoThirds;
twoThirds;
oneThird;
radius;
oneThird;
S 141
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;
S 142
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);
}
}
}
}
2.
3.
4.
5.
6.
A
C
D
C
B
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;
S 143