CS149 – Arrays of Objects
"A computer is like a mischievous genie. It will give you exactly what you ask for, but not always what you want." - Joe Sondow
Review classes and objects
Classes generally include the following kinds of methods (in addition to others):
• constructor methods that initialize new objects
• accessor methods (getters) that return attributes
• mutator methods (setters) that modify attributes
• object methods such as equals and toString
Review
3) Identify an accessor(getter) method in the Point clas
4) Identify a mutator(setter) method in the Point class.
5) The Color class does not have accessors or mutators, but it provides methods that return lighter or darker Color objects. Why do you think the class was designed this way?
Arrays of points
This code will test to see if a test point is in an array of points.
public static boolean found(Point[] pts, Point test) {
boolean located = false;
for(Point p: pts) {
if (p.equals(test)) {
return true;
}
}
return located;
}
import java.awt.Point;
public class TestPoints {
public static void main(String[] args) {
Point a = new Point(0,0);
Point[] points = {a, new Point(1,2), new Point(3,5)};
Point[] points2 = {new Point(3,5), new Point(1,1), new Point(2,2)};
System.out.println("Found test point in array1: " + found(points, a));
System.out.println("Found test point in array2 " + found(points2, a));
}
}
Model 2 Playing Cards
Card Questions
9. Implement the following constructor. The class has two attributes: rank and suit. Don’t think too hard about it.
/**
* Constructs a face card given its rank and suit.
* @param rank face value (1 = ace, 11 = jack, 12 = queen, 13 = king)
* @param suit category ("clubs", "diamonds", "hearts", or "spades")
*/
public Card(int rank, int suit) { }
10. In one line of code,declare an array of strings named suits and initialize its contents to the four possible suits as shown above.
Card Questions Contd.
11. Write several lines of code to declare and create an array of 52 Card objects. Use nested for loops to construct Card objects in the order of the Model. Make use of your suits array from the previous question. How you will keep track of the array index?
12. Describe what the following code does and how it works.(Note:You’ve come a long way this semester, to be able to understand this example!)
public static Card[] sort(Card[] deck) {
if (deck == null) {
System.err.println("Missing deck!");
return null;
}
Card[] sorted = new Card[deck.length];
for (Card card : deck) {
int index = card.position();
sorted[index] = card;
}
return sorted;
}
13. Write a static method named inDeck that takes a Card[] representing a deck of cards and a Card object representing a single card, and that returns true if the card is somewhere in the deck of cards. Be sure to use the equals method of the Card object to make comparisons.
Parts of this activity are based on materials developed by Chris Mayfield and Nathan Sprague.
</end>