Ch9
Ch9
published by Prentice
Hall
Java, Java, Java
Object Oriented Problem Solving
Reference by name
Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 9: Arrays
One-Dimensional Arrays
• An array element is referred to its position within
the array.
• For an n-element array named arr, the elements are
named arr[0], arr[1], arr[2], ...,arr[n-1].
• The following array contains 15 int elements.
Arrays are zero
indexed.
• Invalid References:
arr[5.0] // 5.0 is a float and can't be an array subscript
arr['5'] // '5' is a character not an integer
arr["5"] // "5" is a string not an integer
arr[-1] // Arrays cannot have negative subscripts
arr[15] // The last element of arr has subscript 14
arr[j*k] // Since j*k equals 35
• Debugging Tip:
Creating a new array
does not also create the
objects that are stored in
the array. They must be
instantiated separately.
There are four objects
here. One array and 3
Students.
Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 9: Arrays
Creating an Array of Students
Student student1 = new Student (“Socrates”);
Student student2 = new Student (“Plato”);
Student student3 = new Student (“Aristotle”);
Student school[] = new Student [3];
school[0] = student1;
school[1] = student2;
school[2] = student3;
main() values of 0.
2601 2704 2809 2916 3025 3136 3249 3364 3481 3600
3721 3844 3969 4096 4225 4356 4489 4624 4761 4900
5041 5184 5329 5476 5625 5776 5929 6084 6241 6400
6561 6724 6889 7056 7225 7396 7569 7744 7921 8100
Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 9: Arrays
8281 8464 8649 8836 9025 9216 9409 9604 9801
Generating Random Numbers
• A random number generator generates numbers
that can be used to simulate a coin toss or die roll.
• The numbers generated are pseudorandom.
• Math.random() generates a double value in the
range [0.0, 1.0) -- that is, 0.0 to 0.999999999.
• Using Math.random() to simulate a coin flip:
int coinFlip = (int)(Math.random() * 2); // Heads or tails
public AnalyzeFreq() {
freqArr = new LetterFreq[26];
for (int k = 0; k < 26; k++) {
freqArr[k] = new LetterFreq((char)('A' + k), 0);
} //for
}
public void countLetters(String str) {
char let; //For use in the loop. Note how it uses an
str = str.toUpperCase();
for (int k = 0; k < str.length(); k++) { array of LetterFreq
let = str.charAt(k);
if ((let >= 'A') && (let <= 'Z')) { objects to store letters
freqArr[let - 'A'].incrFreq();
} // if and their frequencies.
} // for
} // countLetters()
Outputs
21 20 27 24 19
19 20 21 24 27
results in: 1 2 4 8
Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 9: Arrays
Design: The Search Class
Uses
Second Second
guess guess
January 5 is
now at
rainfall[1][5]
• Method call: pass the name of the 2-D array to the method:
initRain(rainfall); // Sample method call
/**
* Computes average daily rainfall
* @param rain is a 2D-array of rainfalls
A 2-D array
* @return The sum of rain[x][y] / 356 parameter
* Pre: rain is non null
* Post: The sum of rain / 365 is calculated
* Note that the loops are unit indexed
*/ Nested for loops
public double avgDailyRain(double rain[][]) { iterate 12 x 31 times
double total = 0;
for (int month = 1; month < rain.length; month++)
for (int day = 1; day < rain[month].length; day++)
total += rain[month][day];
return total/365;
} // avgDailyRain() Method call uses the
array’s name.
System.out.println("Daily Avg: " + avgRainForMonth(rainfall));
• Task: Write a
method that can sort
an array of any kind
of object.
An array of
Comparables
// Polymorphic sort method
public static void sort(Comparable[] arr) {
Comparable temp; // Temporary variable for swap
for (int pass = 1; pass < arr.length; pass++) // For each pass
for (int pair = 1; pair < arr.length ; pair++ ) // For ea pair
if (arr[pair].compareTo(arr[pair-1]) < 0) { // Compare
temp = arr[pair-1]; // and swap
arr[pair-1] = arr[pair];
arr[pair] = temp;
} // sort()
} // if
The compareTo()
method is polymorphic.
It is implemented
differently for each
different type of Object.
Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 9: Arrays
OOD: The Comparable Interface
} // main()
Sorted by the same
method.
The
ComputerGame
class uses an
array of Player
objects.
A TwoPlayerGame is a special
case of ComputerGame now.
Abstract methods.
Rewrite the
play()
method.
The new
WordGuesser is
a subclass of
Player.
Java, Java, Java, 3E by R. Morelli | R. Walde Copyright 2006. Chapter 9: Arrays
A GUI-Based Game (Optional)
• We expand the ComputerGame hierarchy to allow GUI-based
games.
• We design a GUIPlayableGame interface to handle the interaction
between the game and the user interface.
Inheritance: SlidingTilePuzzle
inherits ComputerGame and
GUIPlayableGame methods.
Inheritance: SlidingGUI is a
JFrame that uses an array of
JButtons to represent the tiles.