Chapter 15 slides - Fort Thomas Independent Schools

Download Report

Transcript Chapter 15 slides - Fort Thomas Independent Schools

Array Example
[16]
Ingrid
[17]
Darlene
[18]
Gene
[19]
Sean
[20]
Stephanie
[11]
Holly
[12]
Blake
[13]
Michelle
[14]
Remy
[15]
Haley
[06]
Diana
[07]
Jessica
[08]
David
[09]
Anthony
[10]
Alec
[01]
Isolde
[02]
John
[03]
Greg
[04]
Maria
[05]
Heidi
2-D Array Example
[04][01]
Ingrid
[04][02]
Darlene
[04][03]
Gene
[04][04]
Sean
[04][05]
Stephanie
[03][01]
Holly
[03][02]
Blake
[03][03]
Michelle
[03][04]
Remy
[03][05]
Haley
[02][01]
Diana
[02][02]
Jessica
[02][03]
David
[02][04]
Anthony
[02][05]
Alec
[01][01]
Isolde
[01][02]
John
[01][03]
Greg
[01][04]
Maria
[01][05]
Heidi
// Java1501.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.
public class Java1501
{
public static void main(String[ ] args)
{
int twoD[ ][ ];
// declaration of two-dimensional integer array
twoD = new int[2][3];
// new 2D array is constructed with 2 rows and 3 cols
twoD[0][0] = 1;
twoD[0][1] = 2;
twoD[0][2] = 3;
twoD[1][0] = 4;
twoD[1][1] = 5;
twoD[1][2] = 6;
System.out.print(twoD[0][0] + "
System.out.print(twoD[0][1] + "
System.out.print(twoD[0][2] + "
System.out.println();
System.out.print(twoD[1][0] + "
System.out.print(twoD[1][1] + "
System.out.print(twoD[1][2] + "
}
}
");
");
");
");
");
");
// Java1502.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.
public class Java1502
{
public static void main(String[ ] args)
{
int twoD[ ][ ] = new int[2][3]; // 2D array declaration 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();
}
// Java1503.java
// This program demonstrates how to use an initializer list.
// Commented lines 15 and 16 show a matrix style.
public class Java1503
{
public static void main(String[ ] args)
{
int twoD[ ][ ] = { {1,2,3}, {4,5,6} };
// int twoD[ ][ ] = { {1,2,3},
//
{4,5,6} };
for (int row = 0; row < 2; row++)
{
for (int col = 0; col < 3; col++)
{
System.out.print(twoD[row][col] + " ");
}
System.out.println();
}
}
}
To the computer,
these are both
identical.
This also shows
that a 2D array
is an
“array of arrays”.
// Java1504.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.
public class Java1504
{
public static void main(String[ ] args)
{
int k = 1;
int matrix[ ][ ] = new int[7][5]; // 7 rows and 5 columns
for (int r = 0; r < 7; r++)
for (int c = 0; c < 5; c++)
{
matrix[r][c] = k;
k++;
}
System.out.println();
for (int r = 0; r < 5; r++)
{
// should be 7
for (int c = 0; c < 7; c++)
// should be 5
System.out.print(matrix[r][c] + " ");
System.out.println();
}
}
}
System.out.println();
// Java1505.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.
import java.util.Scanner;
// necessary to use the <Scanner> class
public class Java1505
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of rows
--> ");
int numRows = input.nextInt();
System.out.print("Enter the number of columns --> ");
int numCols = input.nextInt();
System.out.println("\n");
int k = 1;
int matrix[][] = new int[numRows][numCols];
for (int r = 0; r < numRows; r++)
for (int c = 0; c < numCols; c++)
{
matrix[r][c] = k;
k++;
}
System.out.println();
for (int r = 0; r < numRows; r++)
{
for (int c = 0; c < numCols; c++)
System.out.print(matrix[r][c] + " ");
System.out.println();
}
System.out.println();
}
}
// Java1506.java
// This program demonstrates the <DecimalFormat> class.
// By using this we can make output line up properly.
import java.text.DecimalFormat; // necessary to use the <DecimalFormat> class
import java.util.Scanner;
// necessary to use the <Scanner> class
public class Java1506
{
public static void main(String args[])
{
DecimalFormat threeDigits = new DecimalFormat("000");
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of rows --> ");
int numRows = input.nextInt();
System.out.print("Enter the number of columns --> ");
int numCols = input.nextInt();
System.out.println("\n");
int k = 1;
int matrix[][] = new int[numRows][numCols]; // 7 rows and 5 columns
for (int r = 0; r < numRows; r++)
for (int c = 0; c < numCols; c++)
{
matrix[r][c] = k;
k++;
}
System.out.println();
for (int r = 0; r < numRows; r++)
{
for (int c = 0; c < numCols; c++)
System.out.print(threeDigits.format(matrix[r][c]) + " ");
System.out.println();
}
System.out.println();
}
}
// Java1507.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.
public class Java1507
{
public static void main(String[ ] args)
{
int[ ][ ] mat = { {1,2,3,4},
{5,6,7,8} };
displayMatrix(mat);
}
public static void displayMatrix(int[ ][ ] matrix)
{
for (int[ ] row : matrix)
{
for (int number : row)
System.out.print(number + " ");
System.out.println();
}
}
}
Close-up View of using
for...each in the Outer Loop
For each array element row in matrix,
which is an int array, do the following ...
for (int[ ] row: matrix)
{
for (int number: row)
System.out.print(threeDigits.format(number) + " ");
System.out.println();
}
Close-up View of using
for...each in the Inner Loop
For each array element number in row,
which is an int, display the number.
for (int[ ] row: matrix)
{
for (int number: row)
System.out.print(threeDigits.format(number) + " ");
System.out.println();
}
for...each
Loop Structure Limitations
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.
Furthermore, the for..each loop will
access every element of the array and
cannot be limited to smaller section.
// Java1508.java
// This program creates a 3 X 3 2D array and uses a method to display the array elements.
// The <length> field is used for both row and column length.
public class Java1508
{
public static void main(String args[])
{
int[][] mat = {{1,2,3},
{4,5,6},
{7,8,9}};
displayMatrix(mat);
}
public static void displayMatrix(int[][] m)
{
for (int r = 0; r < m.length; r++)
{
for (int c = 0; c < m.length; c++)
System.out.print(m[r][c] + " ");
System.out.println();
}
System.out.println();
}
}
// Java1509.java
// The same <displayMatrix> method is used to display a
// 2 X 4 2D array. This time the method does not display correctly.
public class Java1509
{
public static void main(String args[])
{
int[][] mat = { {1,2,3,4},
{5,6,7,8} };
displayMatrix(mat);
}
public static void displayMatrix(int[][] m)
{
for (int r = 0; r < m.length; r++)
{
for (int c = 0; c < m.length; c++)
System.out.print(m[r][c] + " ");
System.out.println();
}
System.out.println();
}
}
2D Array Reality
A two-dimensional array is
actually a one-dimensional
array of one-dimensional
array elements.
// Java1510.java
// A very slight change with the column length results in the correct array display.
public class Java1510
{
public static void main(String args[])
{
int[][] mat = { {1,2,3,4},
{5,6,7,8} };
displayMatrix(mat);
}
public static void displayMatrix(int[][] m)
{
for (int r = 0; r < m.length; r++)
{
for (int c = 0; c < m[0].length; c++)
System.out.print(m[r][c] + " ");
System.out.println();
}
System.out.println();
}
}
The length Field for
2D Non-Ragged Arrays
Consider the following statement:
int matrix[][] = new int[5][4];
The value of matrix.length is 5.
This is the number of rows.
The value of matrix[0].length is 4.
This is the number of columns.
The values of matrix[1].length, matrix[2].length,
matrix[3].length and matrix[4].length are also 4.
Ragged Array Example
[06][01]
Ingrid
[05][01]
Anthony
[04][01]
Holly
[03][01]
John
[02][01]
Diana
[01][01]
Isolde
[06][02]
Darlene
[05][02]
Alec
[04][02]
Blake
[03][02]
Greg
[02][02]
Jessica
[06][03]
Gene
[05][03]
Haley
[04][03]
Michelle
[03][03]
Heidi
[06][04]
Sean
[06][05]
Stephanie
[04][04]
Remy
[03][04]
Maria
[03][05]
David
NOTE:
This is possible because a 2D
array is essentially a 1D array
of 1D arrays, and each 1D
array can be a different size.
// Java1511.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.
public class Java1511
{
public static void main(String args[])
{
int[][] mat = { {1},
{1,2},
{1,2,3},
{1,2,3,4},
{1,2,3,4,5} };
displayMatrix(mat);
}
}
public static void displayMatrix(int[][] m)
{
for (int r = 0; r < m.length; r++)
{
for (int c = 0; c < m[r].length; c++)
System.out.print(m[r][c] + " ");
System.out.println();
}
System.out.println();
}
AP Exam Alert
Two-dimensional ragged arrays, as the
shown in the example below are not tested
on the APCS Examination.
int[][] mat = {{1},
{1,2},
{1,2,3},
{1,2,3,4},
{1,2,3,4,5}};
// Java1512.java
// In this program we explorer the "array of array" concept further.
// Notice how the "2D Array" uses a single set of [ ] index operators.
public class Java1512
{
public static void main(String[ ] args)
{
int[ ][ ] mat = { {1,2,3}, {4,5,6}, {7,8,9} };
System.out.println("mat: " + mat);
System.out.println("mat[0]: " + mat[0]);
System.out.println("mat[1]: " + mat[1]);
System.out.println("mat[2]: " + mat[2]);
}
}
// Java1513.java
// In this program 1D arrays are created first and then used to create a 2D array.
public class Java1513
{
public static void main(String[ ] args)
{
int[ ] list1 = {1,2,3};
int[ ] list2 = {4,5,6};
int[ ] list3 = {7,8,9};
int[ ][ ] mat = new int[3][3];
mat[0] = list1;
mat[1] = list2;
mat[2] = list3;
displayMatrix(mat);
}
}
public static void displayMatrix(int[ ][ ] m)
{
for (int r = 0; r < m.length; r++)
{
for (int c = 0; c < m.length; c++)
System.out.print(m[r][c] + " ");
System.out.println();
}
}
// Java1514.java
// This program demonstrates how to declare a two-dimensional dynamic array.
// It also demonstrates two different output approaches.
import java.util.ArrayList;
public class Java1514
{
public static void main (String args[ ])
{
ArrayList<String> cats = new ArrayList<String>();
cats.add("Lions");
cats.add("Tigers");
ArrayList<String> swimmers = new ArrayList<String>();
swimmers.add("Whales");
swimmers.add("Dolphins");
ArrayList<String> primates = new ArrayList<String>();
primates.add("Gorillas");
primates.add("Chimpanzees");
ArrayList<ArrayList<String>> mammals = new ArrayList<ArrayList<String>>();
mammals.add(cats);
mammals.add(swimmers);
mammals.add(primates);
System.out.println(mammals);
System.out.println();
for (ArrayList<String> mammal: mammals)
{
for (String animal: mammal)
System.out.println(animal);
System.out.println();
}
}
}
// Java1515.java
// This program example demonstrates how to use the original <for>
// loop structure to display dynamic two-dimensional arrays.
import java.util.ArrayList;
public class Java1515
{
public static void main (String args[ ])
{
ArrayList<String> cats = new ArrayList<String>();
cats.add("Lions");
cats.add("Tigers");
ArrayList<String> swimmers = new ArrayList<String>();
swimmers.add("Whales");
swimmers.add("Dolphins");
ArrayList<String> primates = new ArrayList<String>();
primates.add("Gorillas");
primates.add("Chimpanzees");
ArrayList<ArrayList<String>> mammals = new ArrayList<ArrayList<String>>();
mammals.add(cats);
mammals.add(swimmers);
mammals.add(primates);
for (int row = 0; row < mammals.size(); row++)
{
for (int col = 0; col < mammals.get(row).size(); col++)
System.out.println(mammals.get(row).get(col));
System.out.println();
}
}
}
2D Arrays: Dynamic vs Static
for (int row = 0; row < mammals.size(); row++)
{
for (int col = 0; col < mammals.get(row).size(); col++)
System.out.println(mammals.get(row).get(col));
System.out.println();
}
Dynamic
for (int r = 0; r < m.length; r++)
{
for (int c = 0; c < m[0].length; c++)
System.out.print(m[r] [c] + " ");
System.out.println();
}
Static
Calculator Warning
The AP® Computer Science Examination
does not allow the use of calculators.
It is vitally important that you learn to do
all computations on paper.
Counting In Other Number Systems
Counting is something that you will likely take for granted, at least
counting in base-10.
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.
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
107
108
109
However, consider the fact that there are 60 seconds in a minute, 60
minutes in an hour. How about 12 inches to a foot, 3 feet to a yard, and
1,760 yards to a mile. Not everything is done in base-10.
The Odometer Analogy
The odometer is the part of the car that tells you how many
miles you have driven. Example:
3
1
4
2
6
6
Since each place holder can hold 10 possible digits (0-9),
we can say that this odometer is counting in base-10.
If we continued to let it count, we would see the following:
3
1
4
2
6
7
3
1
4
2
7
2
3
1
4
2
6
8
3
1
4
2
7
3
3
1
4
2
6
9
3
1
4
2
7
4
3
1
4
2
7
0
3
1
4
2
7
5
3
1
4
2
7
1
3
1
4
2
7
6
The Broken Odometer
Now suppose somebody decides to remove all of the 8s
and 9s from your car’s odometer.
3
1
4
2
6
6
Since each place holder can hold 8 possible digits (0-7), we
can say that this odometer is counting in base-8.
If we continued to let it count, we would see the following:
3
1
4
2
6
7
3
1
4
2
7
4
3
1
4
2
7
0
3
1
4
2
7
5
3
1
4
2
7
1
3
1
4
2
7
6
3
1
4
2
7
2
3
1
4
2
7
7
3
1
4
2
7
3
3
1
4
3
0
0
Counting Rules for
Numbers of All Bases
There are as many single digits as the base value.
The largest single digit is 1 less than the base value.
You could say that in base N the range of single digits
is from 0 to N-1.
Base 10
Base 9
Base 8
Base 7
Base 6
Base 5
Base 4
Base 3
Base 2
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
0, 1, 2, 3, 4, 5, 6, 7, 8
0, 1, 2, 3, 4, 5, 6, 7
0, 1, 2, 3, 4, 5, 6
0, 1, 2, 3, 4, 5
0, 1, 2, 3, 4
0, 1, 2, 3
0, 1, 2
0, 1
Base 10
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Base 5
0
1
2
3
4
10
11
12
13
14
20
21
22
23
24
30
31
Base 8
0
1
2
3
4
5
6
7
10
11
12
13
14
15
16
17
20
Base 3
0
1
2
10
11
12
20
21
22
100
101
102
110
111
112
120
121
Base 2
0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111
10000
Base 10
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Base 5
32
33
34
40
41
42
43
44
100
101
102
103
104
110
111
112
Base 8
21
22
23
24
25
26
27
30
31
32
33
34
35
36
37
40
Base 3
122
200
201
202
210
211
212
220
221
222
1000
1001
1002
1010
1011
1012
Base 2
10001
10010
10011
10100
10101
10110
10111
11000
11001
11010
11011
11100
11101
11110
11111
100000
List the next 10 base-8 numbers after 321
322 323 324 325 326 327 330 331 332 333
List the next 10 base-8 numbers after 406
407 410 411 412 413 414 415 416 417 420
List the next 10 base-4 numbers after 121
122 123 130 131 132 133 200 201 202 203
List the next 10 base-3 numbers after 11
12 20 21 22 100 101 102 110 111 112
List the next 10 base-2 numbers after 101
110 111 1000 1001 1010 1011 1100 1101 1110 1111
Counting In Base-16
Counting in base-16 is significant in computer science.
You will see that computer memory addresses are
displayed in base-16 or hexadecimal.
A computer’s NIC (Network Interface Card) has a
special address which is a base-16 number.
Future IP addresses will use base-16 as well.
There is a unique relationship between base-2 and
base-16 that we will look at later.
This relationship is the reason base-16 is used in
Assembly Language.
Right now you need to learn how to count in base-16.
The Really Messed Up Odometer
Now suppose somebody decides to add 6 digits (A-F) to
your car’s odometer.
3
A
C
2
6
6
Since each place holder can hold 16 possible digits (0-F),
we can say that this odometer is counting in base-16.
If we continued to let it count, we would see the following:
3
A
C
2
6
7
3
A
C
2
6
C
3
A
C
2
6
8
3
A
C
2
6
D
3
A
C
2
6
9
3
A
C
2
6
E
3
A
C
2
6
A
3
A
C
2
6
F
3
A
C
2
6
B
3
A
C
2
7
0
Counting In Base-16 (continued)
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
List the next 10 base-16 numbers after 100
101 102 103 104 105 106 107 108 109 10a
List the next 10 base-16 numbers after 64
65 66 67 68 69 6a 6b 6c 6d 6e
List the next 10 base-16 numbers after 1001
1002 1003 1004 1005 1006 1007 1008 1009 100a 100b
List the next 10 base-16 numbers after abc
abd abe abf ac0 ac1 ac2 ac3 ac4 ac5 ac6
List the next 10 base-16 numbers after 999
99a 99b 99c 99d 99e 99f 9a0 9a1 9a2 9a3
Flashback to Elementary School
Do you remember learning about the One’s Column,
Ten’s Column, Hundred’s Column’s, Thousand’s column,
etc. back in elementary school.
Understanding how Base-10 works is essential to
understanding how other bases work.
Consider the representation of the number 1,234,567 below:
1,000,000
1
100,000
2
10,000
3
1,000
4
100
5
10
6
1
7
1,000,000
200,000
30,000
4,000
500
60
7
1,000,000 + 200,000 + 30,000 + 4,000 + 500 + 60 + 7 = 1,234,567
Scientific Notation Flashback
Do you remember learning about powers of 10, exponents,
and Scientific Notation. This is also essential.
Consider the representation of the number 1,234,567 below:
1,000,000
106
1
100,000
105
2
10,000
104
3
1,000
103
4
100
102
5
10
101
6
1
100
7
1 * 106
2 * 105
3 * 104
4 * 103
5 * 102
6 * 101
7 * 100
1,000,000
200,000
30,000
4,000
500
60
7
1*106 + 2*105 + 3*104 + 4*103 + 5*102 + 6*101 + 7*100 = 1,234,567
Applying the Rule to Other Bases
Let us see what happens with a base-5 number.
Consider the representation of the number 132045 below:
625
54
1
125
53
3
25
52
2
5
51
0
1
50
4
1 * 54
625
3 * 53
375
2 * 52
50
0 * 51
0
4 * 50
4
13204 base-5 =
1*54 + 3*53 + 2*52 + 0*51 + 4*50 =
625 + 375 + 50 + 0 + 4 =
1,054 base-10
Other Examples
3214 base-5 = 3 x 53 + 2 x 52 + 1 x 51 + 4 x 50
70416 base-8 = 7 x 84 + 0 x 83 + 4 x 82 + 1 x 81 + 6 x 80
5A9D base-16 = 5 x 163 + A x 162 + 9 x 161 + D x 160
3204 base-4 = Incorrect base-4 number
You should notice that once the first step is done – the
expansion step – all that remains is simple arithmetic.
Base-16 is a special case and requires an extra step,
which will be shown on the next slide.
3204 base-4 is intentionally not expanded because it is
not a valid number. Digit 4 is not possible in base-4.
The only 4 digits allowed in base-4 are 0, 1, 2 & 3.
Converting Base-16 to Base-10
1FA base-16 = ??? base-10
The Extra Step
1 * 162 + F * 161 + A * 160 =
After the initial
expansion, use this
chart
Hex Dec
and
A
10
convert
B
11
all
Base-16 C
12
letters
D
13
to their
14
Base-10 E
F
15
values.
1 * 162 + 15 * 161 + 10 * 160 =
1 * 256 + 15 * 16 + 10 * 1 =
256 + 240 + 10 =
506 base-10
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 Q 4 + 4 x Q 3 + 3 x Q2 + 2 x Q1 + 1 x Q0
Converting Base-2 to Base-10
Base 2 is another special case that has a simpler solution
or numbers between 0 and 255 – which are the numbers
currently used in IP Addresses.
Binary (base-2) numbers are frequently written as a
group of 8 bits. The 1st 8 powers of 2 are shown below:
128
64
32
16
8
4
2
1
0
1
0
1
0
1
0
1
To convert the binary number 01010101 to decimal look
for the 1s. Add there place values and ignore the 0s.
01010101 base-2 = 64 + 16 + 4 + 1 = 85 base-10
Another way to look at it
Suppose you have the binary number 11111110
128
64
32
16
8
4
2
1
1
1
1
1
1
1
1
0
One way to do this is by adding place values:
11111110 base-2 =
128 + 64 + 32 + 16 + 8 + 4 + 2 = 254 base-10
If you realize that binary 11111111 = decimal 255
you might find a shorter way to do this by subtracting
place values of the 0s from 255.
11111110 base-2 = 255 - 1 = 254 base-10
The Division Method
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.
This method works for any base. The example on the
next slide demonstrates converting to base-2 for
simplicity. Other examples will follow.
Converting Decimal to Binary
Convert 20110 to binary:
201
100
50
25
12
6
3
1
/
/
/
/
/
/
/
/
2
2
2
2
2
2
2
2
= 100 remainder 1
= 50 remainder 0
= 25 remainder 0
= 12 remainder 1
=
6 remainder 0
=
3 remainder 0
=
1 remainder 1
=
0 remainder 1
When the quotient is 0, take all the remainders in reverse
order for your answer: 20110 = 110010012
Converting Decimal to Base-5
Convert 100110 to Base 5:
1001
200
40
8
1
/
/
/
/
/
5
5
5
5
5
= 200 remainder 1
= 40 remainder 0
=
8 remainder 0
=
1 remainder 3
=
0 remainder 1
When the quotient is 0, take all the remainders in
reverse order for your answer: 100110 = 130015
Converting Decimal to Octal
Convert 235010 to Base 8:
2350
293
36
4
/
/
/
/
8
8
8
8
= 293 remainder 6
= 36 remainder 5
=
4 remainder 4
=
0 remainder 4
When the quotient is 0, take all the remainders in
reverse order for your answer: 235010 = 44568
Converting
Decimal to
Hexadecimal
Using the division
method, when we
take the remainders
in reverse order we
get 1(15)(10).
We need to do one
extra step to make
this right.
Convert 50610 to hexadecimal:
31 r 10
16 )506
48
26
16
10
1 r 15
16 )31
16
15
0 r 1
16 )1
0
1
Converting
Decimal to
Hexadecimal
Extra Step
When the 10 and 15
are converted to A
and F, we can now
properly find the
answer of 1FA.
Convert 50610 to hexadecimal:
31 r 10 = A
16 )506
48
26
16
10
1 r 15 = F
16 )31
16
15
0 r 1
16 )1
0
1
Hex Dec
A
10
B
11
C
D
E
12
13
14
F
15
The
®
AP
Picture Lab
The Picture AP® Labs are different from the other 2 AP®
Labs in a variety of ways. Unlike the Magpie Chatbot
Lab or the Elevens Lab, the Picture AP® Labs
• are more than one lab,
• are completely contained within this chapter,
• are presented in complete form from the start ,
(There are no simple/initial versions.)
• will NOT have its code explained in great detail.
There is a great deal of information hiding used in the
Picture Labs. You will use the provided methods even
if you do not understand their implementation.
The reason these labs are in the 2D Array chapter is that
a picture is a 2D array of colored pixels.
Exposure Java and the AP® Labs
The AP® Computer Science Test Development Committee has coordinated the
creation of these new AP® Labs for the College Board®.
The third AP® Lab, called the AP Picture Lab along with its documentation, is
developed by Barbara Ericson of the Georgia Institute of Technology.
Exposure Java and its Authors Leon Schram (father) and John Schram (son) include
the three AP® labs in this textbook, but had no part in its development.
What has been done in Exposure Java is to present the AP® Labs throughout the
curriculum where appropriate. The labs are not always shown completely, but rather
a smaller sequence of incomplete versions of these labs are introduced to help in
understanding the computer science concepts and Java code presented by each lab.
Even though, the initial lab introductions, and various stages along the way are
different from the AP® labs presented by the College Board®, the final stages shown
in Exposure Java are exactly, like the College Board® versions.
// ColorDemo01.java
// This demo shows the Red, Green and Blue color with their highest (255) intensities.
import java.awt.*;
import java.applet.*;
public class ColorDemo01 extends Applet
{
public void paint(Graphics g)
{
Color brightRed = new Color(255,0,0);
Color brightGreen = new Color(0,255,0);
Color brightBlue = new Color(0,0,255);
System.out.println("Red: " + brightRed);
System.out.println("Green: " + brightGreen);
System.out.println("Blue: " + brightBlue);
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);
}
}
// 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.*;
public class ColorDemo02 extends Applet
{
public void paint(Graphics g)
{
int rndRed = (int) (Math.random() * 255);
int rndGreen = (int) (Math.random() * 255);
int rndBlue = (int) (Math.random() * 255);
Color randomColor = new Color(rndRed,rndGreen,rndBlue);
g.setColor(randomColor);
g.fillRect(50,50,400,400);
g.setColor(Color.black);
g.setFont(new Font("Arial",Font.BOLD,48));
String colorString = "[" + rndRed + "," + rndGreen + "," + rndBlue + "]";
g.drawString(colorString,100,225);
}
}
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 [email protected]
*/
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;
// create a JFrame to be the parent of the color chooser open dialog if you don't do this then you may not see the dialog.
JFrame frame = new JFrame();
frame.setAlwaysOnTop(true);
// use the color chooser to pick the color
color = JColorChooser.showDialog(frame,"Pick a color",color);
return color;
}
/** Main method for testing the ColorChooser */
public static void main(String[ ] args)
{
Color pickedColor = ColorChooser.pickAColor();
System.out.println(pickedColor);
}
}
/**
* Test Main. It will explore the beach
*/
public static void main( String args[])
{
Picture pix = new Picture("beach.jpg");
pix.explore();
}
2 (out of 3) Different
Types of Comments
// This is a single-line comment.
System.out.println("Hello!");
/* This is
// So is this.
/*****************
a multi-line
*
So is this.
*
comment. */
*****************/
Javadoc Comments
Using a method requires
knowledge of the…
• Class identifier
• Method identifier
• Method description (what does it do)
• Method parameter requirements
Javadoc
Files
ColorChooser Javadocs
Picture Javadocs
Group Exercises for 3 or 4 People
With your groups analyze the 11 classes and interface.
Create a hierarchy diagram. This diagram shows
superclasses, subclasses and implementing classes.
There are also independent classes which have no
interaction with any of the other classes. Identify them.
It is not necessary to remember all the many methods,
nor is it necessary to even remember all the classes.
What is necessary is that you can quickly search
through the provided JavaDoc webpages of the AP®
Picture labs and find the class information and the
method information that you require.
Step 1
Load the PictureTester.java file.
Scroll to the bottom of the file and look for the
main method.
You will see many method calls that are all
commented out.
Only testZeroBlue is called.
Step 2
Find method testZeroBlue, which creates a Picture object
with "beach.jpg". Method explore is called twice before and
after blue removal. The zeroBlue method is called to
remove all blue color from the image.
public static void testZeroBlue()
{
Picture beach = new Picture("beach.jpg");
beach.explore();
beach.zeroBlue();
beach.explore();
}
Compile and execute the program.
You should see the two pictures.
Original Beach Picture
With Blue Removed
Step 3
Examine the zeroBlue method.
For this experiment the PictureTester class
and the Picture class have been altered.
Many methods, not necessary for this
experiment were removed, for simplicity.
Load the Picture.java file and find the
zeroBlue method.
Step 4
Method zeroBlue first creates a 2D 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 to 0 for every pixel.
Step 4 Continued
/** Method to set the blue to 0 */
public void zeroBlue()
{
Pixel[][] pixels = this.getPixels2D();
for (Pixel[] rowArray : pixels)
{
for (Pixel pixelObj : rowArray)
{
pixelObj.setBlue(0);
}
}
}
Step 1
Load the PictureTester.java file.
Scroll to the bottom of the file and look for the
main method.
You will see many method calls that are all
commented out.
Uncomment the testGrayScale method by
removing the two comment slashes.
Step 2
Add method testGrayScale to the PictureTester
class at the bottom above main.
public static void testGrayScale()
{
Picture pix = new Picture("beach.jpg");
pix.explore();
pix.grayScale();
pix.explore();
}
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.
The grayScale method does not exist and needs to be created.
Why must it be created in the Picture class and not the
PictureTester class?
Step 4
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 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.
Step 5 Output 1
Step 5 Output 2
Step 5 Output 3
The black and white picture is actually on top of the
color picture. Use your mouse to move it to the side.
Step 1
Observe the pictures on the next several slides
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.
Step 2
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 twodimensional, static int array with an initializer
list. Method displayMatrix is already finished.
You and your partner need to write the mirror
method.
Step 3
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
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 5
Complete method
mirrorHorizontal,
which alters the twodimensional integer
matrix from the original
display, shown at the top,
to the new storage,
shown at the bottom.
Step 6
Complete method
mirrorVertical,
which alters the twodimensional integer
matrix from the original
display, shown at the top,
to the new storage,
shown at the bottom.
Step 7
Complete method
mirrorDiagonal,
which alters the twodimensional integer
matrix from the original
display, shown at the top,
to the new storage,
shown at the bottom.
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.