Professional Documents
Culture Documents
15.1 Introduction
15.2 Declaring a Static 2D Array
15.3 Two-Dimensional Array Output
15.4 2D Arrays and the length Field
15.5 Two-Dimensional Dynamic Arrays
15.6 Introduction to Number Systems
15.6.1 Counting in Other Number Systems
15.6.2 Counting in Base-16
15.6.3 Converting to Base-10
15.6.4 Converting Base-2 to Base-10
15.6.5 Converting Base-10 to Any Base
15.7 The AP® Picture Labs
15.7.1 AP® Picture Experiment 01
15.7.2 AP® Picture Experiment 02
15.7.3 AP® Picture Experiment 03
15.7.4 AP® Picture Experiment 04
15.7.5 AP® Picture Experiment 05
15.7.6 AP® Picture Experiment 06
15.8 Summary
All the array programs – both static arrays and dynamic arrays had something in
common. They have all been examples of one-dimensional (1D) arrays. The term
one-dimensional may have been used a few times without much emphasis on the
concept. It is easier to discuss the dimension of an array when there is the
opportunity to make comparisons. In real life you are surrounded by examples of
both one-dimensional and two-dimensional arrays. A street is a one-dimensional
array of homes. Reserved seats at a football stadium and seats in an airplane
represent a two-dimensional array. Take a look at the seating in figure 15.1. An
array of twenty desks is shown. These twenty desks can be viewed as a linear
sequence of seats, which are numbered from 1 to 20. We could make a closer
analogy to computer language arrays and number the seats from 0 to 19.
However, we can select to represent the seats in a different manner that
realistically resembles the physical desk layout better using a two-dimensional
array.
Figure 15.1
[16] [17] [18] [19] [20]
Jaxon Braxton Remy Michelle Ingrid
[11] [12] [13] [14] [15]
Alec Mariana Mike Haley Maddox
[06] [07] [08] [09] [10]
Diana Jessica Brenda David Anthony
[01] [02] [03] [04] [05]
Isolde John Greg Maria Heidi
The classroom has twenty desks and each desk has a label or index. Labels start at
[01] and end at [20]. This is all simple enough, but the seating chart resembles a
matrix or two-dimensional array more closely. The class has rows and columns.
In fact there are four rows of desks and five columns of desks.
It is possible to designate each student with double labels, one for row and a
second one for column. On the second seating chart, in figure 15.2, you will see
the same classroom and the same desk arrangement, but this time there are two
labels for each seat. The first index, by convention, indicates the row location and
the second index labels the column.
The example of the seating chart actually goes a little against another convention.
Two-dimensional arrays are frequently shown as a matrix of values, and the first
row in the matrix is normally shown at the top of the matrix. This seating chart
has intentionally been displayed from the point of view of the instructor. Using
two values to indicate a location is very common. A Football ticket indicates
something like Row K, Seat 34, and an airline boarding pass may say Row 29,
Seat D. In the world of mathematics, science and business, a matrix of numbers is
used for many types of calculations.
There is only one small difference you will see in program Arrays01.java, shown
in figure 15.3, and that is the need to provide two sets of brackets. The first set of
brackets dimensions the number of rows and the second set of brackets
dimensions the number of columns in the array. In the first 2D array example
every array element is accessed individually. This works, and it is manageable for
a small array of two rows by three columns.
// Arrays01.java
// This program introduces 2D Java static arrays.
// For 2D arrays two sets of index operators are needed.
// The first set of index brackets stores the rows value.
// The second set of index operators stores the cols value.
// Arrays02.java
// A set of nested loops is used with 2D arrays to assign and display individual values.
// Additionally, the declaration of the 2D array is done in one statement.
int count = 1;
for (int row = 0; row < 2; row++)
{
for (int col = 0; col < 3; col++)
{
twoD[row][col] = count;
count++;
}
}
for (int row = 0; row < 2; row++)
{
for (int col = 0; col < 3; col++)
{
System.out.print(twoD[row][col] + " ");
}
System.out.println();
}
}
}
The handy initializer list, shown with the 1D static arrays, also is available for the
2D static arrays. It helps to realize that technically speaking there are no 2D
arrays. A 2D array is really a 1D array where every array element is a 1D array.
In other words, a 2D array is an array of arrays. Program Arrays03.java, in
figure 15.5, uses an initializer list. Observe the comma placement and you see the
array of arrays concept visualized. A second approach, which visually displays
the 2D matrix, is also shown in comments.
// Arrays03.java
// This program demonstrates how to use an initializer list.
// Commented lines 15 and 16 show a matrix style.
Program Arrays04.java, in figure 15.6, may seem similar to earlier programs, but
it displays a very common error that causes array programs to crash during
program execution.
The problem with this program is that the number of rows is confused with the
number of columns. The matrix has 7 rows and 5 columns. When the program
attempts to display 5 rows with 7 columns, the program crashes with a runtime
exception. More information about Java exceptions will be discussed in a later
chapter. The program crashes because an index value is too big.
// Arrays04.java
// This program demonstrates what happens when rows and columns are confused.
// A matrix of 7 rows and 5 columns is created.
// The program attempts to display 5 rows and 7 columns.
// Arrays05.java
// This program allows the user to specify the number of rows and columns.
// Note that the output will not line up nicely as it combines single,
// double and triple digit numbers.
Figure 15.8
// Arrays06.java
// This program demonstrates using <DecimalFormat> with 2D arrays.
// By using <DecimalFormat> we can make output line up properly.
This may seem odd, but there is compelling evidence for this argument. Ask
yourself, what can you store in a one-dimensional array? Well there are numbers,
characters, strings that can be stored and yes you can also store an array in each
element of an existing array. This becomes an array of arrays.
In real life that is actually what happens. Suppose you go to a concert with a
reserved seat ticket. Your ticket states Row H, Seat 17. Now here is a question:
Do you go straight to your seat? I would rather doubt that. Your first mission is to
find Row H. You walk down the aisle and there is H. At this location you are now
looking at a one-dimensional array of seats. This one-dimensional array is called
H. The concert venue is a two-dimensional array of seats, but it can also be called
a one-dimensional array of rows, which then in turn is another one-dimensional
array of seats.
You may be puzzled, because you have just started a section on 2D array output
and this array of arrays seems to go off to some weird tangent. There is a reason
for this explanation. The next program example shows how to use the special
for..each loop with a 2D array. The format of the two-dimensional for..each loop
is based on the array of arrays logic.
Figure 15.9
// Arrays07.java
// This program uses the <for..each> loop structure to display the matrix.
// In this case it is not necessary to use the height and width of the array.
The for..each loop structure is read only for any type of data
structure. This is true for the one-dimensional array as well as
the two-dimensional array.
The length data attribute or field was introduced earlier to determine the number
of elements in a static array. At that time only one-dimensional arrays had been
shown and a natural question is how size is handled with two-dimensional arrays?
Consider program Arrays08.java, in figure 15.10. The length field is used in the
loop, pretty much as it was done with a 1D array. It may seem odd that the same
length value is used for both loops. The output appears correct. Is this the way to
use length? Does it apply both to the number of rows and also to the number of
columns in a 2D array?
This two-dimensional array seems to work quite nicely with the aid of length.
There is a concern though, because a square matrix with three rows and three
columns is used. The same length field is used for row size and column size.
How well will this approach work if the matrix is not square?
Figure 15.11
// Arrays09.java
// The same <displayMatrix> method is used to display a
// 2 X 4 2D array. This time the method does not display correctly.
In the last section it was mentioned that a two-dimensional array is in fact a one-
dimensional array of one-dimensional arrays. Program Arrays10.java, in figure
15.12, takes this new information and tries a different approach. m.length is used
for the row size and then m[0].length is used for the column size.
// Arrays10.java
// A 2D array is a 1D array of arrays.
// This program uses the m[0].length field properly.
// Arrays11.java
// This program demonstrates how to construct an irregular two-dimensional array
// in the shape of a triangle, using a "ragged" array.
// It also shows how to use length for different column sizes.
The new AP® Computer Science curriculum for the 2015 examination places a
special emphasis on the fact that two-dimensional arrays are one-dimensional
arrays. Another, yet different example is shown by Arrays12.java, in figure
15.14. The program starts with the declaration of a two-dimensional array and
then - without any problems - displays separate one-dimensional arrays.
Figure 15.14
// Arrays12.java
// In this program we explorer the "array of array" concept further.
// Notice how the "2D Array" uses a single set of [ ] index operators.
Figure 15.15
// Arrays13.java
// In this program 1D arrays are created first and then used to create a 2D array.
mat[0] = list1;
mat[1] = list2;
mat[2] = list3;
displayMatrix(mat);
}
Figure 15.16
// Arrays14.java
// This program demonstrates how to declare a two-dimensional
// dynamic array.
// It also demonstrates two different output approaches.
import java.util.ArrayList;
System.out.println(mammals);
System.out.println();
Program Arrays15.java, in figure 15.17, gives an idea that dynamic arrays are
more difficult to handle than static arrays for 2D applications. This next program
example is almost identical to the previous program but accesses individual array
locations directly. This is necessary if values have to be altered.
Figure 15.17
// Arrays15.java
// This program example demonstrates how to use the original <for>
// loop structure to display dynamic two-dimensional arrays.
import java.util.ArrayList;
Figure 15.18
Calculator Warning
Counting is something that you will likely take for granted, at least counting in
base-10. This mathematical excursion starts by taking a new look at how we count
in base-10, and how counting is done in other number systems as well. In base-10
there are ten different single digits from 0 to 9. Counting in base-10 requires
cycling through these ten digits. Every time 9 is reached the counting starts over
at 0, and at the same time the digit in the next column is incremented by one.
Consider the following pattern.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
......................................................
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
Using the pattern we observe with base-10 counting lets us set up a set of rules
and then use this set of rules to count in other bases as well. Keep in mind that
there is nothing magic about counting in base-10. Base-10 is only easier for you
The largest single digit is one less than the base value.
The largest digit in base-10 is 9
The largest digit is base-5 is 4
The largest digit in base-8 is 7
The largest digit in base-2 is 1
The largest digit in base-16 is F (base-16 needs digits not used in base-10)
Starting with this first set of exercises you will see a pattern that will be followed
throughout this number system handout. The first group of exercises, 5 in this
case, provide solutions. The second group of exercises are your responsibility
either in class or to do at home.
Exercise 1.1:
List the next 10 base-8 numbers after 321
322 323 324 325 326 327 330 331 332 333
Exercise 1.2:
List the next 10 base-4 numbers after 121
122 123 130 131 132 133 200 201 202 203
Exercise 1.3:
List the next 10 base-2 numbers after 101
110 111 1000 1001 1010 1011 1100 1101 1110 1111
Exercise 1.4:
List the next 10 base-9 numbers after 105
Exercise 1.5:
List the next 10 base-8 numbers after 256
Counting in base-16 is significant in computer science. You will see that all the
computer memory addresses or references are displayed in base-16 or
hexadecimal. Furthermore, the MAC or physical address of a computer is also a
base-16 number. There are unique properties between base-2 and base-16 that
make base-16 a logical choice for number representation in a computer. A few
sections later we will investigate these properties. Right now you need to learn
how to count in base-16.
Base-16 was intentionally not placed in the previous counting section. Every base
in the previous section was smaller than base-10. This was convenient and it
insured that you always used some familiar single digit. The story changes with
base-16 because now it is necessary to fabricate some new single digit numerals.
Base-16 requires the use of 16 single digits. Starting with value 10 base-16 starts
to use letter A and continues with B, C, D, E and F. This looks quite bizarre at
first, but after a while you get used to it. Check out the table below that counts the
first one hundred base-16 numbers.
B-10 B-16 B-10 B-16 B-10 B-16 B-10 B-16 B-10 B-16
1 1 21 15 41 29 61 3d 81 51
2 2 22 16 42 2a 62 3e 82 52
3 3 23 17 43 2b 63 3f 83 53
4 4 24 18 44 2c 64 40 84 54
5 5 25 19 45 2d 65 41 85 55
6 6 26 1a 46 2e 66 42 86 56
7 7 27 1b 47 2f 67 43 87 57
8 8 28 1c 48 30 68 44 88 58
9 9 29 1d 49 31 69 45 89 59
10 a 30 1e 50 32 70 46 90 5a
11 b 31 1f 51 33 71 47 91 5b
12 c 32 20 52 34 72 48 92 5c
13 d 33 21 53 35 73 49 93 5d
14 e 34 22 54 36 74 4a 94 5e
15 f 35 23 55 37 75 4b 95 5f
16 10 36 24 56 38 76 4c 96 60
17 11 37 25 57 39 77 4d 97 61
18 12 38 26 58 3a 78 4e 98 62
19 13 39 27 59 3b 79 4f 99 63
20 14 40 28 60 3c 80 50 100 64
101 102 103 104 105 106 107 108 109 10a
Exercise 2.2:
List the next 10 base-16 numbers after 64
65 66 67 68 69 6a 6b 6c 6d 6e
Exercise 2.3:
List the next 10 base-16 numbers after 1001
1001 1002 1003 1004 1005 1006 1007 1008 1009 100a
Exercise 2.4:
List the next 10 base-16 numbers after abc
Exercise 2.5:
List the next 10 base-16 numbers after 999
The next table is going a step further. This time each place holder will also be
shown as a power of base-10. Row-2 will now represent the power of each place
holder value. Row-3 will show the base and the appropriate exponent. The next
four rows show how the actual value of each place-holding digit is computed.
Row-4 computes the place holder value by raising the base 10 to the indicated
power for its position. Row-5 is the actual single digit that occupies the position
in the number. Row five shows how to multiply the digit times the place holder
value, and the bottom row shows the actual value of a digit after computation.
So far this may seem like a serious what is the big deal anyway? The big deal is
that all numbers in any base can be expressed in expanded notation, and this
expanded notation will be used for conversion between bases. Consider the
following expanded notation for numbers in base-5, base-8, base-16, and base4.
70416 base-8 = 7 x 84 + 0 x 83 + 4 x 82 + 1 x 81 + 6 x 80
If number expansion makes sense to you, you can then take any number in any
base and determine place holder values. You can also create a general method for
expansion for a number with base-Q.
54321 base-Q = 5 x Q4 + 4 x Q3 + 3 x Q2 + 2 x Q1 + 1 x Q0
Perhaps you are wondering what is the use of all of this expansion business is?
Excellent question. With number expansion you can convert a number from any
base into a base-10 number. For instance, let us look at 3214 base-5 again, and
this time we will do some additional calculations beyond the number expansion.
3214 base-5 = 3 x 53 + 2 x 52 + 1 x 51 + 4 x 50
Did that computation make sense? The whole point is that number representation
is the exact same in any base. The only difference is the value of the base. The 3
in 3215 base-5 has a value of 375. The same three in 3215 base-4 has a different
value because the base is different, and the value is 3 x 43 = 3 x 64 = 192.
Check out the following five exercise examples, and then try it on your own.
2 x 42 + 1 x 4 1 + 3 x 40 =
2 x 16 + 1 x 4 + 3 x 1 =
32 + 4 + 3 =
39 base-10
Exercise 3.2:
2134 base-5 = ??? base-10
2 x 53 + 1 x 5 2 + 3 x 51 + 4 x 50 =
2 x 125 + 1 x 25 + 3 x 5 + 4 x 1 =
250 + 25 + 15 + 4 =
294 base-10
Exercise 3.3:
175 base-8 = ??? base-10
1 x 82 + 7 x 8 1 + 5 x 80 =
1 x 64 + 7 x 8 + 5 x 1 =
64 + 56 + 5 =
125 base-10
Base-16 numbers require one extra step. It is not sufficient to use the base-10
place holder values and use them for conversion. The base-16 single digits may
well include values like a, b, c, d, e and f. Any time a base-16 includes such letter
digits, it will be necessary to convert the letter digits to their equivalent base-10
(10, 11, 12, 13, 14 and 15) value before you do any final computations.
Exercise 3.5:
101101 base-2 = ??? base-10
1 x 25 + 0 x 2 4 + 1 x 23 + 1 x 22 + 0 x 21 + 1 x 20 =
1 x 32 + 0 x 16 + 1 x 8 + 1 x 4 + 0 x 2 + 1 x 1 =
32 + 0 + 8 + 4 + 0 + 1 =
45 base-10
Exercise 3.6:
111 base-3 = ??? base-10
Exercise 3.7:
111 base-4 = ??? base-10
Exercise 3.9:
3024 base-5 = ??? base-10
Exercise 3.10:
1111 base-2 = ??? base-10
Observant students may argue that the conversion method for base-2 does not
require all the steps that are used for other numbers. You may note various
shortcuts that can be used. If you know such shortcuts or if you intuitively sense
that there must be a simpler way, well you are completely correct. However, at
this stage the motivation is to demonstrate a common approach that works for any
base that needs to be converted to base-10.
The next section will address the specific nature of converting numbers between
base-2 and base-10. There will also be some special attention devoted to the
relationship between base-2 and base-16 numbers.
This section may seem redundant at first. Earlier in this chapter you were shown
how to convert numbers from any base to base-10. This type of conversion
includes converting base-2 to base-10. It turns out that there is some extra
baggage required for numbers with a base greater than 2 that is not necessary for
base-2 numbers. Consider the following conversion.
It is pretty silly to multiply a number times 1. That made sense with larger base
numbers, but in base-2 there is never a multiply issue. It is also convenient to set
up a chart of binary numbers. You can start on the right with number 1, and
double each number as you move to the left. With such a chart, conversion
becomes easier and more efficient.
Do not think that you should be creating a chart, such as the one above for each
problem that you compute? The point is to take out a piece of scratch paper, write
down a series of binary numbers and write the base-2 number below your chart.
Think of 1 as add, and 0 as skip. Add up all the values below the ones to get the
equivalent base-10 number. The exercises that follow will use the matrix grid to
help neatly identify the number locations. For your own computation the matrix
should not be necessary for each problem.
Exercise 4.2:
10101 base-2 = ??? base-10
128 64 32 16 8 4 2 1
1 0 1 0 1
16 4 1
16 + 4 + 1 = 21 base-10
Exercise 4.3:
10101010 base-2 = ??? base-10
128 64 32 16 8 4 2 1
1 0 1 0 1 0 1 0
128 32 8 2
128 + 32 + 8 + 2 = 170 base-10
Exercise 4.4:
11000000 base-2 = ??? base-10
128 64 32 16 8 4 2 1
1 1 0 0 0 0 0 0
128 64 0 0 0 0 0 0
128 + 64 = 192 base-10
Exercise 4.5:
11100000 base-2 = ??? base-10
128 64 32 16 8 4 2 1
1 1 1 0 0 0 0 0
128 64 32 0 0 0 0 0
128 + 64 + 32 = 224 base-10
It is very common for students to use the trusty expansion method to convert
numbers from base-10 to some other base. This may make sense until you look at
the result and observe what you are doing.
Suppose you want to convert the number 348 base-10 into a base-5 number. Look
what happens with the expansion method.
Well cleverness abounds here. You see how we can very skillfully convert the
348 number with expansion right back into 348. This is not a satisfactory result.
A different approach is necessary.
There are several different ways to convert a base-10 number to another base.
One way involves dividing the base-10 number by the desired base value again
and again until you get a quotient of 0. If you then take all of the remainders in
reverse order, you will have your answer.
You may be surprised that the expansion method is not used in reverse. That
certainly works. You can set up a table with place holder values for each base.
Back in Chapter VIII you were introduced to the Magpie Chatbot AP® Lab. It
then continued with the Elevens AP® Lab, which has been spread over many
chapters and also has not yet concluded. In fact, you have not seen the Elevens
card game at all. Patience, that is in the next chapter. In this chapter the third of
the three AP® Labs, known as the AP® Picture Labs will be presented. Unlike the
other two labs, the Picture programs will be completely contained within this
Two-Dimensional Array chapter.
The Picture Labs are very different from the other two AP® Labs. Both the AP®
Magpie Lab and the AP® Elevens Lab are single labs. Each lab may be an
interaction of multiple classes, but each lab is a single program aiming towards a
specific goal. This is not the case with this third lab and you will see it frequently
mentioned as the AP® Picture Labs (plural).
With the Picture labs you will get considerable practice in manipulating two-
dimensional arrays. Pictures are two-dimensional arrays of pixels and you will do
some interesting lab experiments and lab assignments manipulating pictures.
Along the way you will get considerable practice creating, accessing and altering
two-dimensional arrays. This is the goal of these labs and it is done in a very
fascinating environment of digital photography. It will not take long to realize that
much of the program code is very foreign looking and does not resemble anything
that you have learned earlier. No problem. Your job is to use available methods
from a variety of different classes without concern about the implementation of
these specialized graphics methods.
The Elevens Lab has gone through many chapters to help explain the code and
this code is steadily becoming more complex. With the Picture Labs there is no
initial simple version of the later complex code. You will right away use the
actual Picture Labs code.
Your job is to become familiar with the available functionality of the various
Picture Lab classes with its methods. Then you are expected to take the existing
methods and create new functionalities with digital pictures. At the end you will
have done a variety of interesting programs with digital pictures and along the
way increased your knowledge of two-dimensional arrays.
Picking a Color
Graphics and computers colors are not a new topic. In many chapters you have
seen program examples with graphics displays created by Java program code. The
fundamentals of graphics commands and the fundamentals of color you know
already. What is new in this chapter is that you will be manipulating digital
graphics images that already exist. In other words, it is not your job to write Java
program code that generates some type of graphics display. Rather, you will take
existing digital pictures and manipulate them in many different ways.
In this chapter you also looked at number systems ,which was placed intentionally
prior to this segment of the chapter. Computer colors are a mix of red, green and
blue shades of different intensity. The color values range is [0..255]. Color value
255 shows the brightest color. Load ColorDemo01.java from your Experiment01
folder, shown in figure 15.19. Figure 15.19 shows the applet window graphics
output followed by the text window output of the toString Color method.
Figure 15.19
// ColorDemo01.java
// This demo shows the Red, Green and Blue color with their highest (255) intensities.
import java.awt.*;
import java.applet.*;
g.setColor(brightRed);
g.fillRect(50,100,200,200);
g.setColor(brightGreen);
g.fillRect(300,100,200,200);
g.setColor(brightBlue);
g.fillRect(550,100,200,200);
}
}
Art students - and perhaps people in general - may not quite understand the
computer red, green and blue set of primary colors. When paints are mixed it is
understood that the primary colors are red, blue and yellow. This is not the place
to become technical about color, but mixing paint color and mixing light colors
are not the same. Your art teacher can explain this better than I can and I have
some memory that paint colors are subtractive and computer colors are additive.
What does it all mean? It seems simple to me. In the computer lab write graphics
programs and use primary colors red, green and blue. When you arrive in the art
room and start painting, mix the primary paint colors red, blue and yellow.
It is interesting to note that RGB colors with minimal values zero, have no color
at all and become totally black. When all three RGB colors reach the maximum
color value of 255, the result is white.
Figure 15.20
// ColorDemo02.java
// This color demo shows a new random color and its
// RGB values each time it is executed.
import java.awt.*;
import java.applet.*;
g.setColor(Color.black);
g.setFont(new Font("Arial",Font.BOLD,48));
String colorString = "[" + rndRed + "," + rndGreen + "," + rndBlue + "]";
g.drawString(colorString,100,225);
}
}
Load the ColorChooser.java file in your Java IDE. It is a short program and the
first one of the AP Picture Lab programs. The code is shown in figure 15.21.
Figure 15.21
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import java.awt.Color;
/**
* A class to make working with a color chooser easier
* for students. It uses a JColorChooser to let the user
* pick a color and returns the chosen color object.
*
* @author Barb Ericson ericson@cc.gatech.edu
*/
public class ColorChooser
{
/**
* Method to let the user pick a color and return
* the color object.
* @return the picked color or red if no color was picked
*/
public static Color pickAColor()
{
Color color = Color.white;
return color;
}
Figure 15.22
Click on the RGB tab to get the figure 15.23 screen display. You can now move
the sliders to get different color displays. Note the Color Code window that
shows the RGB color in hexadecimal or base-16 values. The Alpha value is the
degree of transparency or opaqueness. With an alpha value of 0 the image is
totally transparent and with alpha value 255 the image is totally opaque.
Figure 15.23
3. What color do you get when all three RGB values are the same?
Exploring a Picture
This experiment involves a lot more classes. Go to the Experiment02 folder and
then load the PictureExplorer.java file. In figure 15.24 you will only see the end
of the file where the main method is located. For this experiment there is no
concern at all with the Java code and altering any methods. Any changes you
make will only be done in the main method. Compile, then run the program and
you should see a beach picture.
Figure 15.24
/**
* Test Main. It will explore the beach
*/
public static void main( String args[])
{
Picture pix = new Picture("beach.jpg");
pix.explore();
}
}
Right now go ahead and click roughly in the middle of the picture. Figure 15.25 is
a part of the picture to help you see the very small, yellow cross of the mouse-
click location. You will also see that this is coordinate (332,224). Don't get
confused. It is natural to display a pixel as an (x,y) coordinate. However, when we
work with pictures as a two-dimensional array they are handled in row-col order.
There is more information and at the (332,224) location the RGB values are
[125,148,142], which is displayed along with a small square showing that color.
It is also possible to reverse the operation. This time don't click on the picture, but
click on the arrows of the coordinate values. As you alter those values, you will
see the yellow pixel cross move.
Figure 15.25
8. Zoom all the way to 500%. The picture now appears fuzzy, out of focus
and you can see individual large, square pixels. This is a process called
pixelation when pixels become large enough to look like small squares.
11. There is a scale method that can alter the picture size. Construct a new
Picture object using the scale method to get 25% of the picture and
change the program code in the main method of the PictureExplorer
class as shown below:
Picture pix1 = new Picture("astrid1.jpg");
Picture pix2 = pix1.scale(0.25,0.25);
pix2.show();
pix2.write("astrid2.jpg");
You will observe a smaller picture courtesy of the show method.
What does the write method do?
Take a look at the Java program code in figure 15.26. The code has lots of
documentation. In one of the early chapters you learned about documentation for
single lines, such as . . .
// This is a single line comment.
Java also has a third type of comment that is visible in the code below. It looks
like an odd type of multi-line comment, but it is more than a comment in the
program code. It has some special properties.
Figure 15.26
We are in the middle of the AP Picture Labs and there are many programs to look
at, experiments to perform and also some lab assignments to complete. All this
work revolves around manipulating digital pictures, which are essentially 2D
arrays of pixels. Manipulating these pictures is done with many classes and within
these many classes are even more methods. This can get quite confusing.
Furthermore, you are not really expected to learn the program code of these many
methods, but you do need to know how to use the methods. This requires the
following information.
Class identifier
Method identifier
Method description (what does it do)
Method parameter requirements
The first two experiments with the AP Picture Labs were done without this
information. The reality is that for Experiment01 and Experiment02 you strictly
used existing programs. You were looking at different colors and you were
exploring a picture. In other words, you were not at the level of a programmer.
Now the experiments change. You are expected to create new methods in existing
classes to manipulate pictures. Creating these methods requires the use of many
specialized methods that already exist. Making sense of all these classes and
methods is the web-based documentation that exists for the AP Picture Labs. First
find the Experiment03 folder, shown in figure 15.27 and then open the lone
PicturesJavaDoc folder shown in figure 15.28. The web-page contents of the
PicturesJavaDoc folder are shown incompletely. Look for the index.html file.
All the files in PicturesJavaDoc are web pages of the classes in the AP Picture
Labs. They do not contain the program code, but specific documentation about the
classes and methods that the programmer wanted to be easily visible. To see this
documentation double-click on index.html.
Figure 15.29 shows the initial view of the Web-Based documentation that was
created for AP Picture Labs. In the left window 11 classes are displayed and 1
interface. The interface, DigitalPicture, is italicized. The main window shows the
current class or interface that is chosen. In this case it is ColorChooser.
Much can be said about this documentation, but right now scroll up and down.
Check out the details of the constructor, the data fields and the methods.
Figure 15.29
Figure 15.30 shows the Picture class. This class will become important in future
experiments. Do the same thing. Scroll, check out some method and see what
information you can find.
The number of classes that are part of the AP Pictures Labs are numerous and the
methods are even greater in number. Don't worry about memorizing all the
details. Your first job is to get an overview what is available. Ten classes and one
interface follow.
A snapshot of the web page is shown and it shows that part that indicates the
name of the class, a diagram of the class hierarchy and its subclasses. What does
hierarchy mean? It is a pyramid structure with a superclass and its subclasses. In
the Catholic Church the Pope is at the top of the hierarchy, followed by the
Bishops who each are in charge of a Diocese, which in turn consists of parishes
that are manned by Priests.
Each short snapshot also provides a short description of the class. Again don't try
to remember. Knowing that there exists a summary in this chapter helps and you
will find that the actual web pages are available with various Lab Experiments
where the information is needed.
Step 1
Step 2
Step 4
Step 5
Method zeroBlue first must create a pixels array with method getPixels2D.
You will not find getPixels2D in the Picture class.
Look in the superclass of Picture, SimplePicture; you will find it there.
Many other methods are found in SimplePicture class as well.
The for..each loop is used to access each individual Pixel object of the array.
You will also need to examine the Pixel class, which will be used frequently.
The setBlue method of the Pixel class is used to set the blue value to 0 for every pixel.
Use the following code and write it into the Return to the PictureTester class.
zeroBlue method of the Picture class. Re-compile and re-execute the program
and now the second beach picture will
public void zeroBlue() have all the blue removed from every
{ pixel and looks like the picture below.
Pixel[][] pixels =
this.getPixels2D();
for (Pixel[] rowArray: pixels)
{
for (Pixel pixelObj:rowArray)
{
pixelObj.setBlue(0);
}
}
}
Step 1
Step 2
Add method testGrayScale to the PictureTester class at the bottom above main.
Step 3
The PictureTester class is only concerned with creating Picture objects and testing
them with some new method. All that has been done so far is call method
testGrayScale. In that method a new Picture object is constructed.
The object pix then calls method explore, which displays the image.
The explore method already exists in the PictureExplorer class.
Much of what you will do involves knowing what exists - and can be used - and knowing
what does not exist and must be created.
Black & White pictures are not pictures with groups of pixels that are black or white.
These pictures display pixels with shades of gray. There are 256 shades of gray. Each
gray shade is created with the same values for red, green and blue. (0,0,0) is totally
black. (100,100,100) is a medium shade of gray.
Here are steps necessary to turn a colored picture into a black & white picture:
Create a two-dimensional array pixels object. Pixel objects store color values.
Access each pixel in the array and get the three color values.
Add up the three color values of the pixel.
Divide this color sum by three to get the average color, which is the gray value.
Assign the equivalent gray color to the pixel.
Step 5
In your groups create the grayScale method. Do not be afraid to use trial & error. It is
not necessary to have the complete and correct solution in your head before you start.
We learn a lot from incorrect program code.
The first picture below is the beach.jpg with the original color picture.
The second picture shows the converted black and white version of beach.jpg.
When you execute the program, the pictures will be on top of each other.
You can drag them besides each other to make comparisons.
Mirror Images
You saw with the grayScale experiment how a colored image can be altered to a
black & white picture. Specialized methods were used to access individual pixels
and then access and alter pixel color values. None of this is a possibility without
knowledge of manipulating two-dimensional arrays. A digital image is a two-
dimensional array of individual pixels and each pixel store a red, green and blue
value to create a very large variety of colors. At the conclusion of this chapter you
will do a lab assignment that involves altering digital pictures.
Observe the pictures below which are taken from your future lab assignment. In this
experiment you will write various methods that manipulate two-dimensional, number
arrays. You will find that the algorithms you create to alter the arrays will follow the
same logic when you start to alter the pictures.
Open the Experiment06 folder and load the Mirror01st.java. The file is shown below
and it is the first of five array-altering experiments. Each one of the five programs will
create a two-dimensional, static int array with an initializer list. Method displayMatrix
is already finished. You and your partner need to write the mirror method.
Your objective is to complete the program by writing method mirror. The end result is
a display of two matrixes. The top matrix is the original array created with the initializer
list. The second matrix is the appearance after executing your mirror method.
Step 4
, whiuch
Step 6
Step 8
Little was stated about array size in the previous five experiements. All the matrixes
were square-sized. That is required for the mirrorDiagonal method, but the others
only require a rectangular matrix.
Consider odd-sized and even sized matrixes. If your solutions work well for the
provided matrix size, will it work also when you change the size?
Perhaps your teacher already had you change sizes with each experiment, but if you
completed each experiment successfully, with the provided matrix, try it again. Change
any even-sized to odd-sized and change the odd-sized to even-sized and see if you
methods still perform correctly.
Two-dimensional arrays, or matrixes, are all around you. You see it in your
classroom with the desks. You see it at concerts and football stadiums. You see it
when you get on an airplane and check your boarding pass for your seat. You see
it when you open a spreadsheet and look at many rows and many columns of data.
Computers simulate life and the two-dimensional array in Java simulates many of
the common aspects of your daily routine.
Dynamic two-dimensional arrays are possible with the ArrayList class, but they
are not so commonly used. The old-fashioned, index brackets, static arrays is the
first choice for most programmers.
Counting in all number systems is based on starting at zero and counting to one
less than the base, which is the largest single digit. After the largest single digit is
reached, a system is used where by each digit has a place-holder value that
increases by the value of the base. For instance in base-10 we have the following
place holders that are single digits with values that are powers of the base.
1 2 3 4 5 6 7 8
10,000,000 1,000,000 100,000 10,000 1000 100 10 1
In base there are only two digits, 1 and 0. The place holder values now increase as
a power of the base 2.
1 1 1 1 1 1 1 1
128 64 32 16 8 4 2 1
When a number has a base larger than 10, it is necessary to create new single
digit. In the case of base-16, letter are used.
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
F E D C B A 9 8 7 6 5 4 3 2 1 0
Digital images are two-dimensional arrays of pixels. Each pixel stores the red,
green and blue values of the pixel. Knowledge of various methods that get the
pixel colors and sets the pixels colors can be combined with 2D Array
manipulations to alter images.
For instance the color gray is a mix of three identical red, green and blue values.
Color (0,0,0) is the darkest black. Color (255,255,255) is pure white and the color
(100,100,100) is a shade of gray. Program code can be written to access the color
values of each pixel in a digital image. If the average color value is switched to a
shade of gray for each pixel in a color picture, the image become black&white
picture.
Pixel values can also be copied to other sections of the image to create mirror
images. In one technique of a symmetrical building, like a temple, an old picture
with a roof, broken on one side can be digitally repaired. The whole, left side, of
the roof can be mirror copied unto the broken, right side of the roof to create a
picture that resembles the original building.
This altered picture gives an impression of the original temple. The mirror image
is strictly local to the roof only. Note how the bushes are the same in both
pictures.