March 21st, 2016
Lab
Classwork:
Activity 9: Questions 1 through 3
Homework:
Activity 10: Implementing the Thirteens Board
Exercise 1, 2 and 3
AP Exam 2012 Question 3
March 22nd, 2016
Classwork:
Activity 9: Questions 3 short discussion
Quick Interfaces Review:
• All methods in an interface type are abstract; that is, they have a name, parameters, and a return type, but they don’t have an implementation.
• All methods in an interface type are automatically public.
• An interface type does not have instance variables, but it is legal to specify constants.
How is the correct method executed when the interface method is invoked?
How did the correct method get called if the caller didn’t even know the exact class to which meas belongs?
The Java virtual machine locates the correct method by first looking at the class of the actual object, and then calling the method with the given name in that class.
This means that one method call can invoke different methods depending on the momentary contents of an interface variable. This mechanism for locating the appropriate method is called dynamic method look-up.
Dynamic method look-up enables a programming technique called polymorphism. The term polymorphism comes from the Greek words for “many shapes”. The same computation works for objects of many shapes, and adapts itself to the nature of the objects.
Activity 11 – Simulation of Elevens: Exercises 1, 2 and 3
Homework:
Activity 11: Simulation of Elevens
Exercise 4, and 5
AP Exam 2012 Question 4
In this activity, you will complete a Card class that will be used to create card objects.
Think about card games you’ve played. What kinds of information do these games require a card object to “know”? What kinds of operations do these games require a card object to provide?
Now think about implementing a class to represent a playing card. What instance variables should it have? What methods should it provide? Discuss your ideas for this Card class with classmates.
Read the partial implementation of the Card class available in the Activity1 Starter Code folder. As you read through this class, you will notice the use of the @Override annotation before the toString method. The Java @Override annotation can be used to indicate that a method is intended to override a method in a superclass.
In this example, the Object class’s toString method is being overridden in the Card class. If the indicated method doesn’t override a method, then the Java compiler will give an error message.
Here’s a situation where this facility comes in handy. Programmers new to Java often encounter problems matching headings of overridden methods to the superclass’s original method heading. For example, in the Weight class below, the tostring method is intended to be invoked when toString is called for a Weight object.
public class Weight {
private int pounds;
private int ounces;
…
public String tostring(String str) {
return this.pounds + ” lb. ” + this.ounces + ” oz.”;
}
…
}
Unfortunately, this doesn’t work; the tostring method given above has a different name and a different signature from the Object class’s toString method. The correct version below has the correct name toString and no parameter:
public String toString() {
return this.pounds + ” lb. ” + this.ounces + ” oz.”;
}
The @Override annotation would cause an error message for the first tostring version to alert the programmer of the errors.
Exercises:
1. Complete the implementation of the provided Card class. You will be required to complete:
a. a constructor that takes two String parameters that represent the card’s rank and suit, and an int parameter that represents the point value of the card;
b. accessor methods for the card’s rank, suit, and point value;
c. a method to test equality between two card objects; and
d. the toString method to create a String that contains the rank, suit, and point value of the card object.
The string should be in the following format:
rank of suit (point value = pointValue)
/** Sample Output:
The rank of the first card is: Queen
The suit of the first card is: Hearts
The point value of the first card is: 12
In summary, the first card is the Queen of Hearts (12)
The rank of the second card is: Five
The suit of the second card is: Spades
The point value of the second card is: 5
In summary, the second card is the Five of Spades (5)
The rank of the third card is: Five
The suit of the third card is: Spades
The point value of the third card is: 5
In summary, the third card is the Five of Spades (5)
The first card and the second card are not equivalent.
The second card and the third card are equivalent.
The first card and the third card are not equivalent.
*/
Introduction:
Think about a deck of cards. How would you describe a deck of cards? When you play card games, what kinds of operations do these games require a deck to provide?
Exploration:
Now consider implementing a class to represent a deck of cards. Describe its instance variables and methods, and discuss your design with a classmate.
Read the partial implementation of the Deck class available in the Activity 2 Starter Code folder. This file contains the instance variables, constructor header, and method headers for a Deck class general enough to be useful for a variety of card games.
Discuss the Deck class with your classmates; in particular, make sure you understand the role of each of the parameters to the Deck constructor, and of each of the private instance variables in the Deck class.
Exercises:
1. Complete the implementation of the Deck class by coding each of the following:
• Deck constructor — This constructor receives three arrays as parameters. The arrays contain the ranks, suits, and point values for each card in the deck. The constructor creates an ArrayList, and then creates the specified cards and adds them to the list.
For example, if ranks = {“A”, “B”, “C”}, suits = {“Giraffes”, “Lions”}, and values = {2,1,6}, the constructor would create the following cards:
[“A”, “Giraffes”, 2], [“B”, “Giraffes”, 1], [“C”, “Giraffes”, 6], [“A”, “Lions”, 2], [“B”, “Lions”, 1], [“C”, “Lions”, 6]
and would add each of them to cards. The parameter size would then be set to the size of cards, which in this example is 6.
Finally, the constructor should shuffle the deck by calling the shuffle method. Note that you will not be implementing the shuffle method until Activity 4.
• isEmpty — This method should return true when the size of the deck is 0; false otherwise.
• size — This method returns the number of cards in the deck that are left to be dealt.
• deal — This method “deals” a card by removing a card from the deck and returning it, if there are any cards in the deck left to be dealt. It returns null if the deck is empty. There are several ways of accomplishing this task. Here are two possible algorithms:
Algorithm 1: Because the cards are being held in an ArrayList, it would be easy to simply call the List method that removes an object at a specified index, and return that object. Removing the object from the end of the list would be more efficient than removing it from the beginning of the list. Note that the use of this algorithm also requires a separate “discard” list to keep track of the dealt cards. This is necessary so that the dealt cards can be reshuffled and dealt again.
Algorithm 2: It would be more efficient to leave the cards in the list. Instead of removing the card, simply decrement the size instance variable and then return the card at size. In this algorithm, the size instance variable does double duty; it determines which card to “deal” and it also represents how many cards in the deck are left to be dealt. This is the algorithm that you should implement.
Questions:
1. Explain in your own words the relationship between a deck and a card.
String[] ranks = {“jack”, “queen”, “king”};
String[] suits = {“blue”, “red”};
int[] pointValues = {11, 12, 13};
Deck d = new Deck(ranks, suits, pointValues);
Deck d = new Deck(ranks, suits, pointValues);
initializes a deck for a Twenty-One game.
/** TESTING
Testing deck1
deck1 size: 3
deck1 deal: three of hearts (point value = 3)
deck1 size: 2
Is deck1 empty?: false
Testing deck2
deck2 size: 1
deck2 deal: ten of diamonds (point value = 10)
deck2 size: 0
Is deck2 empty?: true
Testing deck3
deck3 size: 2
deck3 deal: queen of clubs (point value = 12)
deck3 size: 1
Is deck3 empty?: false
*/
Picture Lab – Activity 6
Mirroring pictures
Exercises:
1. Write the method mirrorVerticalRightToLeft that mirrors a picture around a mirror placed vertically from right to left. Hint: you can copy the body of mirrorVertical and only change one line in the body of the method to accomplish this. Write a class (static) test method called testMirrorVerticalRightToLeft in PictureTester to test this new method and call it in the main method.
Write the method mirrorHorizontal that mirrors a picture around a mirror placed horizontally at the middle of the height of the picture. Mirror from top to bottom as shown in the pictures below (Figure 8). Write a class (static) test method in PictureTester to test this new method and call it in the main method.
Write the method mirrorHorizontalBotToTop that mirrors the picture around a mirror placed horizontally from bottom to top. Hint: you can copy the body of mirrorHorizontal and only change one line to accomplish this. Write a class (static) test method in PictureTester to test this new method and call it in the main method.
Challenge — Work in groups to figure out the algorithm for the method mirrorDiagonal that mirrors just a square part of the picture from bottom left to top right around a mirror placed on the diagonal line (the diagonal line is the one where the row index equals the column index). This will copy the triangular area to the left and below the diagonal line as shown below. This is like folding a square piece of paper from the bottom left to the top right, painting just the bottom left triangle and then (while the paint is still wet) folding the paper up to the top right again. The paint would be copied from the bottom left to the top right as shown in the pictures below (Figure 9). Write a class (static) test method in PictureTester to test this new method and call it in the main method.
April 27th, 2015
Picture Lab
A9: Simple edge detection
Detecting edges is a common image processing problem. For example, digital cameras often feature face detection. Some robotic competitions require the robots to find a ball using a digital camera, so the robot needs to be able to “see” a ball.
One way to look for an edge in a picture is to compare the color at the current pixel with the pixel in the next column to the right. If the colors differ by more than some specified amount, this indicates that an edge has been detected and the current pixel color should be set to black. Otherwise, the current pixel is not part of an edge and its color should be set to white (Figure 12). How do you calculate the difference between two colors?
public void edgeDetection(int edgeDist) { Pixel leftPixel = null; Pixel rightPixel = null; Pixel[][] pixels = this.getPixels2D(); Color rightColor = null; for (int row = 0; row < pixels.length; row++) { for (int col = 0; col < pixels[0].length-1; col++) { leftPixel = pixels[row][col]; rightPixel = pixels[row][col+1]; rightColor = rightPixel.getColor(); if (leftPixel.colorDistance(rightColor) > edgeDist) leftPixel.setColor(Color.BLACK); else leftPixel.setColor(Color.WHITE); } } }
Classwork:
Exercises
1. Notice that the current edge detection method works best when there are big color changes from left to right but not when the changes are from top to bottom. Add another loop that compares the current pixel with the one below and sets the current pixel color to black as well when the color distance is greater than the specified edge distance.
2. Work in groups to come up with another algorithm for edge detection.
How image processing is related to new scientific breakthroughs
Many of today’s important scientific breakthroughs are being made by large, interdisciplinary collaborations of scientists working in geographically widely distributed locations, producing, collecting, and analyzing vast and complex datasets.
One of the computer scientists who works on a large interdisciplinary scientific team is Dr. Cecilia Aragon. She is an associate professor in the Department of Human Centered Design & Engineering and the eScience Institute at the University of Washington, where she directs the Scientific Collaboration and Creativity Lab. Previously, she was a computer scientist in the Computational Research Division at Lawrence Berkeley National Laboratory for six years, after earning her Ph.D. in Computer Science from UC Berkeley in 2004. She earned her B.S. in mathematics from the California Institute of Technology.
Her current research focuses on human-computer interaction (HCI) and computer-supported cooperative work (CSCW) in scientific collaborations, distributed creativity, information visualization, and the visual understanding of very large data sets. She is interested in how social media and new methods of computer-mediated communication are changing scientific practice. She has developed novel visual interfaces for collaborative exploration of very large scientific data sets, and has authored or co-authored many papers in the areas of computer-supported cooperative work, human-computer interaction, visualization, visual analytics, image processing, machine learning, cyberinfrastructure, and astrophysics.
In 2008, she received the Presidential Early Career Award for Scientists and Engineers (PECASE) for her work in collaborative data-intensive science. Her research has been recognized with four Best Paper awards since 2004, and she was named one of the Top 25 Women of 2009 by Hispanic Business Magazine. She was the architect of the Sunfall data visualization and workflow management system for the Nearby Supernova Factory, which helped advance the study of supernovae in order to reduce the statistical uncertainties on key cosmological parameters that categorize dark energy, one of the grand challenges in physics today.
Cecilia Aragon is also one of the most skilled aerobatic pilots flying today. A two-time member of the U.S. Aerobatic Team, she was a medalist at the 1993 U.S. National Championships and the 1994 World Aerobatic Championships, and was the California State Aerobatic Champion.
THE END
April 23rd, 2015
Picture Lab – Activity 7
Mirroring pictures
Classwork:
Activity 7:
A7: Mirroring part of a picture
public void mirrorTemple() { int mirrorPoint = 276; Pixel leftPixel = null; Pixel rightPixel = null; int count = 0; Pixel[][] pixels = this.getPixels2D(); // loop through the rows for (int row = 27; row < 97; row++) { // loop from 13 to just before the mirror point for (int col = 13; col < mirrorPoint; col++) { leftPixel = pixels[row][col]; rightPixel = pixels[row][mirrorPoint - col + mirrorPoint]; rightPixel.setColor(leftPixel.getColor()); } } }
Questions
1. How many times would the body of this nested for loop execute?
for (int row = 7; row < 17; row++) for (int col = 6; col < 15; col++)
2. How many times would the body of this nested for loop execute?
for (int row = 5; row <= 11; row++) for (int col = 3; col <= 18; col++)
Exercises
1. Check the calculation of the number of times the body of the nested loop executes by adding an integer count variable to the mirrorTemple method that starts out at 0 and increments inside the body of the loop. Print the value of count after the nested loop ends.
2. Write the method mirrorArms to mirror the arms on the snowman (“snowman.jpg”) to make a snowman with 4 arms. Write a class (static) test method in PictureTester to test this new method and call it in the main method.
3. Write the method mirrorGull to mirror the seagull (“seagull.jpg”) to the right so that there are two seagulls on the beach near each other. Write a class (static) test method in PictureTester to test this new method and call it in the main method.
Homework:
A8: Creating a collage
public void copy(Picture fromPic, int startRow, int startCol) { Pixel fromPixel = null; Pixel toPixel = null; Pixel[][] toPixels = this.getPixels2D(); Pixel[][] fromPixels = fromPic.getPixels2D(); for (int fromRow = 0, toRow = startRow; fromRow < fromPixels.length && toRow < toPixels.length; fromRow++, toRow++) { for (int fromCol = 0, toCol = startCol; fromCol < fromPixels[0].length && toCol < toPixels[0].length; fromCol++, toCol++) { fromPixel = fromPixels[fromRow][fromCol]; toPixel = toPixels[toRow][toCol]; toPixel.setColor(fromPixel.getColor()); } } }
public void createCollage() { Picture flower1 = new Picture("flower1.jpg"); Picture flower2 = new Picture("flower2.jpg"); this.copy(flower1,0,0); this.copy(flower2,100,0); this.copy(flower1,200,0); Picture flowerNoBlue = new Picture(flower2); flowerNoBlue.zeroBlue(); this.copy(flowerNoBlue,300,0); this.copy(flower1,400,0); this.copy(flower2,500,0); this.mirrorVertical(); this.write("collage.jpg"); }
Exercises
1. Create a second copy method that adds parameters to allow you to copy just part of the fromPic. You will need to add parameters that specify the start row, end row, start column, and end column to copy from. Write a class (static) test method in PictureTester to test this new method and call it in the main method.

2. Create a myCollage method that has at least three pictures (can be the same picture) copied three times with three different picture manipulations and at least one mirroring. Write a class (static) test method in PictureTester to test this new method and call it in the main method.
April 19th, 2016
Picture Lab – Activity 5
Classwork:
1. Open Picture.java and look for the method getPixels2D. Is it there?
2. Open SimplePicture.java and look for the method getPixels2D. Is it there?
3. Does the following code compile?
DigitalPicture p = new DigitalPicture();
4. Assuming that a no-argument constructor exists for SimplePicture, would the following
code compile?
DigitalPicture p = new SimplePicture();
5. Assuming that a no-argument constructor exists for Picture, does the following code
compile?
DigitalPicture p = new Picture();
6. Assuming that a no-argument constructor exists for Picture, does the following code
compile?
SimplePicture p = new Picture();
7. Assuming that a no-argument constructor exists for SimplePicture, does the following
code compile?
Picture p = new SimplePicture();
More Questions:
List
Why wouldn’t you just declare nameList to be of the type ArrayList
What do you think you will see if you modify the beach picture in the images folder to set all the blue values to zero?
Do you think you will still see a beach?
Exercises
1. Open PictureTester.java and run its main method. You should get the same results as running the main method in the Picture class. The PictureTester class contains class (static) methods for testing the methods that are in the Picture class.
2. Uncomment the appropriate test method in the main method of PictureTester to test any of the other methods in Picture.java. You can comment out the tests you don’t want to run. You can also add new test methods to PictureTester to test any methods you create in the Picture class.
Homework:
Exercises
3. Using the zeroBlue method as a starting point, write the method keepOnlyBlue that will keep only the blue values, that is, it will set the red and green values to zero. Create a class (static) method to test this new method in the class PictureTester. Be sure to call the new test method in the main method in PictureTester.
4. Write the negate method to negate all the pixels in a picture. To negate a picture, set the red value to 255 minus the current red value, the green value to 255 minus the current green value and the blue value to 255 minus the current blue value. Create a class (static) method to test this new method in the class PictureTester. Be sure to call the new test method in the main method in PictureTester.
5. Write the grayscale method to turn the picture into shades of gray. Set the red, green, and blue values to the average of the current red, green, and blue values (add all three values and divide by 3). Create a class (static) method to test this new method in the class PictureTester. Be sure to call the new test method in the main method in PictureTester.
6. Challenge — Explore the “water.jpg” picture in the images folder. Write a method fixUnderwater() to modify the pixel colors to make the fish easier to see. Create a class (static) method to test this new method in the class PictureTester. Be sure to call the new test method in the main method in PictureTester.
A4: Two-dimensional arrays in Java
Exercises
Questions
Homework:
Picture Lab Activity 3
Exercises
Picture p = new Picture("myPicture.jpg"); Picture smallP = p.scale(0.25,0.25); smallP.write("smallMyPicture.jpg");
Questions
1. How many bits does it take to represent the values from 0 to 255?
2. How many bytes does it take to represent a color in the RBG color model?
3. How many pixels are in a picture that is 640 pixels wide and 480 pixels high?
A2: Picking a color
Questions
1. How can you make pink?
2. How can you make yellow?
3. How can you make purple?
4. How can you make white?
5. How can you make dark gray?
Homework
Picture Lab Activity
Finish up A1 and A2