Two –Dimensional Arrays
Download
Report
Transcript Two –Dimensional Arrays
Two –Dimensional Arrays
Mrs. C. Furman
Java Programming
November 19, 2008
Two Dimensional Arrays
rows and columns, also called a Matrix
we must specify the number of row and columns
we will need when we construct the 2DArray.
Similar to Arrays.
0 1 2 3
Example:
int [][] magicSquare = new int [4][4]; 0 0 0 0 0
1 0 0 0 0
2
0 0 0 0
3
0 0 0 0
Accessing Elements in a 2D Array
Elements are indexed [row][column]
magicSquare [0][0] = 3;
magicSquare [1][3] = 5;
int myNum = magicSquare [1][3];
0
1
2
3
0
3 0
0 0
1
0 0
0 5
2
0 0
0 0
3
0 0 0 0
Initializer List for 2D
int [][]cars = {{10, 7, 12, 10, 4},
{18, 11, 15, 17, 10},
{12, 10, 9, 5, 12},
{16, 6, 13, 8, 3}};
red
brown black white gray
GM
10 7
12 10 4
Ford
18 11 15 17 10
Toyota
12 10 9
BMW
16 6
5
13 8
12
3
Getting Size
.length gives us the number of rows…
then when we access a specific row, we
do .length to get number of columns.
int[][] list = {{1,2,3, 4}, {1}, {1, 2, 3}};
int numRows = list.length;//3
int firstCol = list[0].length;//4
int secCol = list[1].length;//1
int thirdCol = list[2].length;//3
Looping Through a 2D Array
Example 3: Write a nested for loop to output all
elements in the 2D array.
for (int row = 0; row < list.length; row++)
{
for (int col = 0; col< list[row].length; col++)
{
System.out.print (list [row][col] + “ “);
}
System.out.println ();
}
Multiplication Table
Write a loop that will assign a 5 x 5 2D Array to
the multiplication tables of 0 ..4.
The result will look like the below 2D Array
0
1
2
3
4
0 0
0
0
0
0
1 0
1
2
3
4
2 0
2
4
6
8
3 0
3
6
9
12
4 0
4
8
12 16
Picture Encoding
Bitmap images: each dot or pixel is
represented separately.
Pictures are 2-D arrays of pixels.
We will be dealing with .jpg (jpeg) files
Each pixel in a picture has a color
The dimension of the picture is measured
in pixels.
JPEG’s
High quality pictures with smaller storage.
JPEG is a lossy compression format.
Lossy compression: it is compressed,
made smaller, but not with 100% of the
quality of the original.
Typically what gets thrown out is the stuff
that you don’t see or notice anyway, so the
quality is still considered high.
Color
RGB color model.
Pixels are encoded with three numbers, 1st
for the amount of red, 2nd for the amount of
green, and 3rd for the amount of blue
We can make any humanly visible color by
combining different amounts of red, green
and blue.
Combining all 3 together to get white,
remove all 3 to get black.
(0,0,0) – black; (255, 255, 255) - white
Some Color examples
(255, 0, 0) – red
(100, 0, 0) – darker red
(0, 100, 0) – dark green
(0, 0 , 100) – dark blue
All 3 the same… we get gray…
(50, 50,50) – dark gray
(150, 150, 150) – lighter gray