When we first discussed Picture representation, we noted that there were two ways of representing a Picture: as a matrix of pixels and as a single array of pixels. While the former is more intuitive, we examined the latter first as it was simpler to deal with in terms of programming.
Now that we have the basics of working with loops, we’ll be able to work with the matrix version of a picture. This switch will require us to nest loops within each other, a topic you will be introduced to in this reading.
Section 5.1.1 (pp. 131-134) from the course textbook.
Each student will be responsible for learning and demonstrating proficiency in the following objectives PRIOR to the class meeting. The reading quiz will test these objectives.
getPixel
method.for
loops.The following objectives should be mastered by each student DURING and FOLLOWING the class session through active work and practice.
These exercises are geared towards mastering the BASIC learning objectives listed above. You are expected to submit them before class and it is highly recommended that you complete them before attempting the reading quiz.
Assume that we have the following Picture variable declaration and initialization:
Picture myPic = new Picture(FileChooser.pickAFile());
Write Java expressions that use the getPixel
method to get each of the following Pixel objects.
A pixel at a random location in the Picture object. Assume that you have a random number generator (RNG) object, as declared below, that you can use to generate a random numbers like you did in PSA2.
Random rng = new Random();
For each of the following sets of nested loops, draw a diagram to illustrate which pixels are modified and the order in which they are modified.
// Nested loops 1
for (int x = 0; x < this.getWidth(); x++)
{
for (int y = 0; y < this.getHeight(); y++)
{
Pixel p = this.getPixel(x,y);
p.setRed(0);
}
}
// Nested loops 2
for (int y = 0; y < this.getHeight(); y++)
{
for (int x = 0; x < this.getWidth(); x++)
{
Pixel p = this.getPixel(x,y);
p.setRed(0);
}
}
// Nested loops 3
for (int x = 0; x < this.getWidth(); x = x + 2)
{
for (int y = 0; y < this.getHeight(); y++)
{
Pixel p = this.getPixel(x,y);
p.setRed(0);
}
}
// Nested loops 4
for (int x = 0; x < this.getWidth()/2; x = x + 2)
{
for (int y = 0; y < this.getHeight(); y = y + 2)
{
Pixel p = this.getPixel(x,y);
p.setRed(0);
}
}