SlideShare uma empresa Scribd logo
1 de 31
Chapter 7 Multidimensional Arrays




    Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                         rights reserved.
                                                                                                   1
Motivations
Thus far, you have used one-dimensional arrays to model linear
collections of elements. You can use a two-dimensional array to
represent a matrix or a table. For example, the following table that
describes the distances between the cities can be represented using a
two-dimensional array.
                                            Distance Table (in miles)

                 Chicago         Boston         New York            Atlanta       Miami          Dallas       Houston

   Chicago              0           983               787              714           1375         967          1087
   Boston             983             0               214             1102           1763        1723          1842
   New York           787           214                 0              888           1549        1548          1627
   Atlanta           714           1102               888               0             661         781          810
   Miami            1375           1763              1549             661              0         1426          1187
   Dallas             967          1723              1548             781            1426           0          239

   Houston          1087           1842              1627             810           1187          239           0
                        1723              1548              781           1426             0            239
              Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                   rights reserved.
                                                                                                                        2
Objectives
   To give examples of representing data using two-dimensional arrays
    (§7.1).
   To declare variables for two-dimensional arrays, create arrays, and
    access array elements in a two-dimensional array using row and column
    indexes (§7.2).
   To program common operations for two-dimensional arrays (displaying
    arrays, summing all elements, finding min and max elements, and
    random shuffling) (§7.3).
   To pass two-dimensional arrays to methods (§7.4).
   To write a program for grading multiple-choice questions using two-
    dimensional arrays (§7.5).
   To solve the closest-pair problem using two-dimensional arrays (§7.6).
   To check a Sudoku solution using two-dimensional arrays (§7.7).
   To use multidimensional arrays (§7.8).
              Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                   rights reserved.
                                                                                                             3
Declare/Create Two-dimensional Arrays
// Declare array ref var
dataType[][] refVar;

// Create array and assign its reference to variable
refVar = new dataType[10][10];

// Combine declaration and creation in one statement
dataType[][] refVar = new dataType[10][10];

// Alternative syntax
dataType refVar[][] = new dataType[10][10];



         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                              rights reserved.
                                                                                                        4
Declaring Variables of Two-
     dimensional Arrays and Creating
        Two-dimensional Arrays
int[][] matrix = new int[10][10];
or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;

for (int i = 0; i < matrix.length; i++)
  for (int j = 0; j < matrix[i].length; j++)
    matrix[i][j] = (int)(Math.random() * 1000);

double[][] x;
         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                              rights reserved.
                                                                                                        5
Two-dimensional Array Illustration
    [0] [1] [2] [3] [4]                          [0] [1] [2] [3] [4]                                             [0] [1] [2] [3]
    4
[0] 0 0 0 0 0                                [0] 4 0 0 0 0 0                                            [0]      1     2    3

[1]   0 0     0   0    0                      [1]      0 0         0      0     0                       [1]       4    5    6

[2]   0   0   0   0    0                     [2]       0     7     0     0      0                       [2]       7     8   9

[3]   0 0     0   0    0                      [3]      0 0         0      0     0                       [3]      10    11   12

[4]   0 0     0   0    0                     [4]       0 0         0      0     0                       [4]
                                                                                                         int[][] array = {
                                                                                                            {1, 2, 3},
matrix = new int[5][5];                        matrix[2][1] = 7;                                            {4, 5, 6},
                                                                                                            {7, 8, 9},
                                                                                                            {10, 11, 12}
                                                                                                          };


      matrix.length? 5                                                                         array.length? 4
      matrix[0].length? 5                                                                      array[0].length? 3

                  Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                       rights reserved.
                                                                                                                             6
Declaring, Creating, and Initializing Using
              Shorthand Notations
You can also use an array initializer to declare, create and
 initialize a two-dimensional array. For example,

int[][] array = {
                                                         int[][] array = new int[4][3];
 {1, 2, 3},                                              array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
 {4, 5, 6},                    Same as                   array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
 {7, 8, 9},                                              array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
 {10, 11, 12}                                            array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
};




                    Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                         rights reserved.
                                                                                                                   7
Lengths of Two-dimensional
                      Arrays
    int[][] x = new int[3][4];
x
                                    x[0][0] x[0][1] x[0][2] x[0][3]                                  x[0].length is 4
    x[0]
    x[1]                            x[1][0] x[1][1] x[1][2] x[1][3]                                  x[1].length is 4

    x[2]
                                    x[2][0] x[2][1] x[2][2] x[2][3]                                   x[2].length is 4
x.length is 3




                Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                     rights reserved.
                                                                                                                         8
Lengths of Two-dimensional
          Arrays, cont.
int[][] array = {                                                array.length
 {1, 2, 3},                                                      array[0].length
 {4, 5, 6},                                                      array[1].length
 {7, 8, 9},                                                      array[2].length
 {10, 11, 12}                                                    array[3].length
};

 array[4].length                     ArrayIndexOutOfBoundsException

        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                             rights reserved.
                                                                                                       9
Ragged Arrays
Each row in a two-dimensional array is itself an array. So,
   the rows can have different lengths. Such an array is
   known as a ragged array. For example,
int[][] matrix = {
 {1, 2, 3, 4, 5},                  matrix.length is 5
 {2, 3, 4, 5},                    matrix[0].length is 5
                                  matrix[1].length is 4
 {3, 4, 5},                       matrix[2].length is 3
 {4, 5},                          matrix[3].length is 2
 {5}                              matrix[4].length is 1

};
           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                          10
Ragged Arrays, cont.


int[][] triangleArray = {                                                                      1 2 3 4   5
  {1, 2, 3, 4, 5},
  {2, 3, 4, 5},                                                                                2 3 4 5
  {3, 4, 5},
  {4, 5},                                                                                      3 4 5
  {5}
};                                                                                             4 5

                                                                                               5




        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                             rights reserved.
                                                                                                         11
Processing Two-Dimensional Arrays
See the examples in the text.
1.   (Initializing arrays with input values)
2.   (Printing arrays)
3.   (Summing all elements)
4.   (Summing all elements by column)
5.   (Which row has the largest sum)
6.   (Finding the smallest index of the largest element)
7.   (Random shuffling)

           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                          12
Initializing arrays with input values
java.util.Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and " +
  matrix[0].length + " columns: ");
for (int row = 0; row < matrix.length; row++) {
  for (int column = 0; column < matrix[row].length; column++) {
    matrix[row][column] = input.nextInt();
  }
}




             Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                  rights reserved.
                                                                                                            13
Initializing arrays with random values

for (int row = 0; row < matrix.length; row++) {
  for (int column = 0; column < matrix[row].length; column++) {
    matrix[row][column] = (int)(Math.random() * 100);
  }
}




             Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                  rights reserved.
                                                                                                            14
Printing arrays
for (int row = 0; row < matrix.length; row++) {
 for (int column = 0; column < matrix[row].length; column++) {
   System.out.print(matrix[row][column] + " ");
 }

    System.out.println();
}




                Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                     rights reserved.
                                                                                                               15
Summing all elements
int total = 0;
for (int row = 0; row < matrix.length; row++) {
  for (int column = 0; column < matrix[row].length; column++) {
    total += matrix[row][column];
  }
}




             Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                  rights reserved.
                                                                                                            16
Summing elements by column
for (int column = 0; column < matrix[0].length; column++) {
  int total = 0;
  for (int row = 0; row < matrix.length; row++)
   total += matrix[row][column];
  System.out.println("Sum for column " + column + " is "
   + total);
}




           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                          17
Random shuffling
for (int i = 0; i < matrix.length; i++) {
  for (int j = 0; j < matrix[i].length; j++) {
    int i1 = (int)(Math.random() * matrix.length);
    int j1 = (int)(Math.random() * matrix[i].length);
    // Swap matrix[i][j] with matrix[i1][j1]
    int temp = matrix[i][j];
    matrix[i][j] = matrix[i1][j1];
    matrix[i1][j1] = temp;
  }
}
          Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                               rights reserved.
                                                                                                         18
Passing Tow-Dimensional Arrays to
            Methods




                                                     PassTwoDimensionalArray

                                                                                                    Run

     Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                          rights reserved.
                                                                                                          19
Problem: Grading Multiple-
                 Choice Test
                                                                               Objective: write a
              Students’ Answers to the Questions:
              0 1 2 3 4 5 6 7 8 9
                                                                                program that grades
Student   0   A   B   A    C   C    D    E   E    A   D                         multiple-choice test.
Student   1   D   B   A    B   C    A    E   E    A   D
Student   2   E   D   D    A   C    B    E   E    A   D
Student   3   C   B   A    E   D    C    E   E    A   D                           Key to the Questions:
Student   4   A   B   D    C   C    D    E   E    A   D                           0 1 2 3 4 5 6 7 8 9
Student   5   B   B   E    C   C    D    E   E    A   D
Student   6   B   B   A    C   C    D    E   E    A   D           Key             D B D C C D A E A D
Student   7   E   B   E    C   C    D    E   E    A   D




                                                                     GradeExam                               Run
              Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                   rights reserved.
                                                                                                                   20
Problem: Finding Two Points
     Nearest to Each Other
                                                                                                               x    y
                                                                                                          0   -1   3
 (-1, 3)
                                          (3, 3)                                                          1   -1 -1
                                                                                                          2    1   1
                                                 (4, 2)
                   (1, 1)
                                                                                                          3    2 0.5
                                                                                                          4    2 -1
                                   (2, 0.5)
                                                                                                          5    3   3
                                                (4, -0.5)                                                 6    4   2
(-1, -1)                          (2, -1)                                                                 7    4 -0.5



                                                       FindNearestPoints                                      Run
           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                                    21
What is Sudoku?

5 3           7
6         1 9        5
    9 8                         6
8             6                       3
4         8          3                1
7             2                       6
    6
          4 1        9                5
              8                  7 9




                  Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                       rights reserved.
                                                                                                                 22
Every row contains the numbers 1 to 9

5 3           7                                                          5     3     4     6     7     8     9   1   2
6         1 9        5                                                   6     7     2     1     9     5     3   4   8
    9 8                         6                                        1     9     8     3     4     2     5   6   7
8             6                       3                                  8     5     9     7     6     1     4   2   3
4         8          3                1                                  4     2     6     8     5     3     7   9   1
7             2                       6                                  7     1     3     9     2     4     8   5   6
    6                                                                    9     6     1     5     3     7     2   8   4
          4 1        9                5                                  2     8     7     4     1     9     6   3   5
              8                  7 9                                     3     4     5     2     8     6     1   7   9




                  Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                       rights reserved.
                                                                                                                         23
Every column contains the numbers 1 to 9

5 3           7                                                          5     3     4     6     7     8     9   1   2
6         1 9        5                                                   6     7     2     1    9      5     3   4   8
    9 8                         6                                        1     9    8      3     4     2     5   6   7
8             6                       3                                  8     5     9     7     6     1     4   2   3
4         8          3                1                                  4     2     6     8     5     3     7   9   1
7             2                       6                                  7     1     3     9     2     4     8   5   6
    6                                                                    9 6         1     5     3     7     2   8   4
          4 1        9                5                                  2     8     7     4    1      9     6   3   5
              8                  7 9                                     3     4     5     2     8     6     1   7   9




                  Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                       rights reserved.
                                                                                                                         24
Every 3×3 box contains the numbers 1 to 9

5 3           7                                                          5     3     4     6     7     8     9   1   2
6         1 9        5                                                   6     7     2     1    9      5     3   4   8
    9 8                         6                                        1     9    8      3     4     2     5   6   7
8             6                       3                                  8     5     9     7     6     1     4   2   3
4         8          3                1                                  4     2     6     8     5     3     7   9   1
7             2                       6                                  7     1     3     9     2     4     8   5   6
    6                                                                    9 6         1     5     3     7     2   8   4
          4 1        9                5                                  2     8     7     4    1      9     6   3   5
              8                  7 9                                     3     4     5     2     8     6     1   7   9




                  Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                       rights reserved.
                                                                                                                         25
Checking Whether a Solution Is Correct
   5 3                7                                       5 3 4            6 7         8    9         1 2
   6             1 9         5                                6 7 2            1 9         5    3 4         8
       9 8                             6                      1 9 8            3 4         2    5 6         7
   8                  6                       3               8 5 9            7 6         1    4 2         3
   4             8           3                1               4 2 6            8 5         3 7 9            1
   7                  2                       6               7 1 3            9 2         4    8 5         6
       6                                                      9 6 1            5 3         7    2         8 4
                 4 1         9                5               2 8 7            4 1         9    6         3 5
                      8                 7 9                   3 4 5            2 8         6    1         7 9




                       CheckSudokuSolution                                                Run

           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                                26
Multidimensional Arrays
Occasionally, you will need to represent n-
dimensional data structures. In Java, you can create
n-dimensional arrays for any integer n.

The way to declare two-dimensional array
variables and create two-dimensional arrays can be
generalized to declare n-dimensional array
variables and create n-dimensional arrays for n >=
3.

         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                              rights reserved.
                                                                                                        27
Multidimensional Arrays
 double[][][] scores = {
  {{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}},
  {{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}},
  {{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}},
  {{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}},
  {{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}},
  {{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}}};


Which student                          Which exam                               Multiple-choice or essay




                   scores[ i ] [ j ] [ k ]

             Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                  rights reserved.
                                                                                                            28
Problem: Calculating Total Scores

   Objective: write a program that calculates the total score for
    students in a class. Suppose the scores are stored in a three-
    dimensional array named scores. The first index in scores refers to
    a student, the second refers to an exam, and the third refers to the
    part of the exam. Suppose there are 7 students, 5 exams, and each
    exam has two parts--the multiple-choice part and the programming
    part. So, scores[i][j][0] represents the score on the multiple-choice
    part for the i’s student on the j’s exam. Your program displays the
    total score for each student.


                                                                     TotalScore                              Run
              Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                   rights reserved.
                                                                                                                   29
Problem: Weather Information
 Suppose    a meteorology station records the
    temperature and humidity at each hour of every day
    and stores the data for the past ten days in a text file
    named weather.txt. Each line of the file consists of
    four numbers that indicate the day, hour, temperature,
    and humidity. Your task is to write a program that
    calculates the average daily temperature and humidity
    for the 10 days.
1 1 76.4 0.92                                 10 24 98.7 0.74
1 2 77.7 0.93                                 1 2 77.7 0.93
...                                           ...
10 23 97.7 0.71                               10 23 97.7 0.71                                                  Weather
10 24 98.7 0.74                               1 1 76.4 0.92

                                                                    (b)
          (a)
                                                                                                               Run
                Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                     rights reserved.
                                                                                                                     30
Problem: Guessing Birthday
 Listing3.8, GuessBirthday.java, gives a
 program that guesses a birthday. The program
 can be simplified by storing the numbers in
 five sets in a three-dimensional array, and it
 prompts the user for the answers using a loop,
 as shown in Listing 7.6. The sample run of the
 program can be the same as shown in Listing
 3.8.


                  GuessBirthdayUsingArray                                                              Run
        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                             rights reserved.
                                                                                                             31

Mais conteúdo relacionado

Mais procurados

Some fixed point theorems in generalised dislocated metric spaces
Some fixed point theorems in generalised dislocated metric spacesSome fixed point theorems in generalised dislocated metric spaces
Some fixed point theorems in generalised dislocated metric spacesAlexander Decker
 
A Study on Intuitionistic Multi-Anti Fuzzy Subgroups
A Study on Intuitionistic Multi-Anti Fuzzy Subgroups A Study on Intuitionistic Multi-Anti Fuzzy Subgroups
A Study on Intuitionistic Multi-Anti Fuzzy Subgroups mathsjournal
 
L1 Sudoku
L1 SudokuL1 Sudoku
L1 Sudokubnmoran
 
D E S I G N A N D A N A L Y S I S O F A L G O R I T H M S J N T U M O D E L...
D E S I G N A N D A N A L Y S I S O F A L G O R I T H M S  J N T U  M O D E L...D E S I G N A N D A N A L Y S I S O F A L G O R I T H M S  J N T U  M O D E L...
D E S I G N A N D A N A L Y S I S O F A L G O R I T H M S J N T U M O D E L...guest3f9c6b
 
How queries work with sharding
How queries work with shardingHow queries work with sharding
How queries work with shardingMongoDB
 
Course module of DS
Course module of DSCourse module of DS
Course module of DSPCTE
 
Some New Operations on Fuzzy Soft Sets
Some New Operations on Fuzzy Soft SetsSome New Operations on Fuzzy Soft Sets
Some New Operations on Fuzzy Soft SetsIJMER
 
MDX - What BI Developers Need To Know
MDX - What BI Developers Need To KnowMDX - What BI Developers Need To Know
MDX - What BI Developers Need To KnowMark Ginnebaugh
 
Gaussian Processes: Applications in Machine Learning
Gaussian Processes: Applications in Machine LearningGaussian Processes: Applications in Machine Learning
Gaussian Processes: Applications in Machine Learningbutest
 
On generalized dislocated quasi metrics
On generalized dislocated quasi metricsOn generalized dislocated quasi metrics
On generalized dislocated quasi metricsAlexander Decker
 
11.on generalized dislocated quasi metrics
11.on generalized dislocated quasi metrics11.on generalized dislocated quasi metrics
11.on generalized dislocated quasi metricsAlexander Decker
 
Lesson 19: Optimization Problems
Lesson 19: Optimization ProblemsLesson 19: Optimization Problems
Lesson 19: Optimization ProblemsMatthew Leingang
 
International Journal of Computer Science and Security Volume (3) Issue (4)
International Journal of Computer Science and Security Volume (3) Issue (4)International Journal of Computer Science and Security Volume (3) Issue (4)
International Journal of Computer Science and Security Volume (3) Issue (4)CSCJournals
 

Mais procurados (20)

Some fixed point theorems in generalised dislocated metric spaces
Some fixed point theorems in generalised dislocated metric spacesSome fixed point theorems in generalised dislocated metric spaces
Some fixed point theorems in generalised dislocated metric spaces
 
Lecture7 data structure(tree)
Lecture7 data structure(tree)Lecture7 data structure(tree)
Lecture7 data structure(tree)
 
A Study on Intuitionistic Multi-Anti Fuzzy Subgroups
A Study on Intuitionistic Multi-Anti Fuzzy Subgroups A Study on Intuitionistic Multi-Anti Fuzzy Subgroups
A Study on Intuitionistic Multi-Anti Fuzzy Subgroups
 
L1 Sudoku
L1 SudokuL1 Sudoku
L1 Sudoku
 
JavaYDL8
JavaYDL8JavaYDL8
JavaYDL8
 
D E S I G N A N D A N A L Y S I S O F A L G O R I T H M S J N T U M O D E L...
D E S I G N A N D A N A L Y S I S O F A L G O R I T H M S  J N T U  M O D E L...D E S I G N A N D A N A L Y S I S O F A L G O R I T H M S  J N T U  M O D E L...
D E S I G N A N D A N A L Y S I S O F A L G O R I T H M S J N T U M O D E L...
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
 
Metric Embeddings and Expanders
Metric Embeddings and ExpandersMetric Embeddings and Expanders
Metric Embeddings and Expanders
 
How queries work with sharding
How queries work with shardingHow queries work with sharding
How queries work with sharding
 
13slide graphics
13slide graphics13slide graphics
13slide graphics
 
Course module of DS
Course module of DSCourse module of DS
Course module of DS
 
Some New Operations on Fuzzy Soft Sets
Some New Operations on Fuzzy Soft SetsSome New Operations on Fuzzy Soft Sets
Some New Operations on Fuzzy Soft Sets
 
CS 354 Typography
CS 354 TypographyCS 354 Typography
CS 354 Typography
 
MDX - What BI Developers Need To Know
MDX - What BI Developers Need To KnowMDX - What BI Developers Need To Know
MDX - What BI Developers Need To Know
 
Gaussian Processes: Applications in Machine Learning
Gaussian Processes: Applications in Machine LearningGaussian Processes: Applications in Machine Learning
Gaussian Processes: Applications in Machine Learning
 
Daa q.paper
Daa q.paperDaa q.paper
Daa q.paper
 
On generalized dislocated quasi metrics
On generalized dislocated quasi metricsOn generalized dislocated quasi metrics
On generalized dislocated quasi metrics
 
11.on generalized dislocated quasi metrics
11.on generalized dislocated quasi metrics11.on generalized dislocated quasi metrics
11.on generalized dislocated quasi metrics
 
Lesson 19: Optimization Problems
Lesson 19: Optimization ProblemsLesson 19: Optimization Problems
Lesson 19: Optimization Problems
 
International Journal of Computer Science and Security Volume (3) Issue (4)
International Journal of Computer Science and Security Volume (3) Issue (4)International Journal of Computer Science and Security Volume (3) Issue (4)
International Journal of Computer Science and Security Volume (3) Issue (4)
 

Destaque (20)

JavaYDL3
JavaYDL3JavaYDL3
JavaYDL3
 
JavaYDL4
JavaYDL4JavaYDL4
JavaYDL4
 
JavaYDL12
JavaYDL12JavaYDL12
JavaYDL12
 
JavaYDL19
JavaYDL19JavaYDL19
JavaYDL19
 
JavaYDL11
JavaYDL11JavaYDL11
JavaYDL11
 
JavaYDL6
JavaYDL6JavaYDL6
JavaYDL6
 
JavaYDL2
JavaYDL2JavaYDL2
JavaYDL2
 
JavaYDL1
JavaYDL1JavaYDL1
JavaYDL1
 
JavaYDL9
JavaYDL9JavaYDL9
JavaYDL9
 
11slide
11slide11slide
11slide
 
JavaYDL5
JavaYDL5JavaYDL5
JavaYDL5
 
History of languages'
History of languages'History of languages'
History of languages'
 
10slide
10slide10slide
10slide
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good Parts
 
History of java'
History of java'History of java'
History of java'
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
Creativity and Copywriting - Radio
Creativity and Copywriting - RadioCreativity and Copywriting - Radio
Creativity and Copywriting - Radio
 

Semelhante a JavaYDL7 (20)

JavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptJavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.ppt
 
Array in c language
Array in c languageArray in c language
Array in c language
 
Multi dimensional arrays
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arrays
 
06slide
06slide06slide
06slide
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
Java™ (OOP) - Chapter 6: "Arrays"
Java™ (OOP) - Chapter 6: "Arrays"Java™ (OOP) - Chapter 6: "Arrays"
Java™ (OOP) - Chapter 6: "Arrays"
 
Array
ArrayArray
Array
 
C arrays
C arraysC arrays
C arrays
 
Plc (1)
Plc (1)Plc (1)
Plc (1)
 
Array
ArrayArray
Array
 
Arrays in CPP
Arrays in CPPArrays in CPP
Arrays in CPP
 
CS.3.Arrays.pdf
CS.3.Arrays.pdfCS.3.Arrays.pdf
CS.3.Arrays.pdf
 
Introducing R
Introducing RIntroducing R
Introducing R
 
Plc (1)
Plc (1)Plc (1)
Plc (1)
 
C Language Lecture 10
C Language Lecture 10C Language Lecture 10
C Language Lecture 10
 
Introduction to R r.nabati - iausdj.ac.ir
Introduction to R   r.nabati - iausdj.ac.irIntroduction to R   r.nabati - iausdj.ac.ir
Introduction to R r.nabati - iausdj.ac.ir
 
Array
ArrayArray
Array
 
Lecture 6
Lecture 6Lecture 6
Lecture 6
 
Java arrays
Java    arraysJava    arrays
Java arrays
 
L10 array
L10 arrayL10 array
L10 array
 

Mais de Terry Yoast

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12Terry Yoast
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11Terry Yoast
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10Terry Yoast
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09Terry Yoast
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08Terry Yoast
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07Terry Yoast
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06Terry Yoast
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05Terry Yoast
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04Terry Yoast
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03Terry Yoast
 
9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02Terry Yoast
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01Terry Yoast
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13Terry Yoast
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18Terry Yoast
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17Terry Yoast
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16Terry Yoast
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15Terry Yoast
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14Terry Yoast
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12Terry Yoast
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11Terry Yoast
 

Mais de Terry Yoast (20)

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03
 
9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11
 

Último

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 

Último (20)

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 

JavaYDL7

  • 1. Chapter 7 Multidimensional Arrays Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1
  • 2. Motivations Thus far, you have used one-dimensional arrays to model linear collections of elements. You can use a two-dimensional array to represent a matrix or a table. For example, the following table that describes the distances between the cities can be represented using a two-dimensional array. Distance Table (in miles) Chicago Boston New York Atlanta Miami Dallas Houston Chicago 0 983 787 714 1375 967 1087 Boston 983 0 214 1102 1763 1723 1842 New York 787 214 0 888 1549 1548 1627 Atlanta 714 1102 888 0 661 781 810 Miami 1375 1763 1549 661 0 1426 1187 Dallas 967 1723 1548 781 1426 0 239 Houston 1087 1842 1627 810 1187 239 0 1723 1548 781 1426 0 239 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 2
  • 3. Objectives  To give examples of representing data using two-dimensional arrays (§7.1).  To declare variables for two-dimensional arrays, create arrays, and access array elements in a two-dimensional array using row and column indexes (§7.2).  To program common operations for two-dimensional arrays (displaying arrays, summing all elements, finding min and max elements, and random shuffling) (§7.3).  To pass two-dimensional arrays to methods (§7.4).  To write a program for grading multiple-choice questions using two- dimensional arrays (§7.5).  To solve the closest-pair problem using two-dimensional arrays (§7.6).  To check a Sudoku solution using two-dimensional arrays (§7.7).  To use multidimensional arrays (§7.8). Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 3
  • 4. Declare/Create Two-dimensional Arrays // Declare array ref var dataType[][] refVar; // Create array and assign its reference to variable refVar = new dataType[10][10]; // Combine declaration and creation in one statement dataType[][] refVar = new dataType[10][10]; // Alternative syntax dataType refVar[][] = new dataType[10][10]; Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 4
  • 5. Declaring Variables of Two- dimensional Arrays and Creating Two-dimensional Arrays int[][] matrix = new int[10][10]; or int matrix[][] = new int[10][10]; matrix[0][0] = 3; for (int i = 0; i < matrix.length; i++) for (int j = 0; j < matrix[i].length; j++) matrix[i][j] = (int)(Math.random() * 1000); double[][] x; Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 5
  • 6. Two-dimensional Array Illustration [0] [1] [2] [3] [4] [0] [1] [2] [3] [4] [0] [1] [2] [3] 4 [0] 0 0 0 0 0 [0] 4 0 0 0 0 0 [0] 1 2 3 [1] 0 0 0 0 0 [1] 0 0 0 0 0 [1] 4 5 6 [2] 0 0 0 0 0 [2] 0 7 0 0 0 [2] 7 8 9 [3] 0 0 0 0 0 [3] 0 0 0 0 0 [3] 10 11 12 [4] 0 0 0 0 0 [4] 0 0 0 0 0 [4] int[][] array = { {1, 2, 3}, matrix = new int[5][5]; matrix[2][1] = 7; {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; matrix.length? 5 array.length? 4 matrix[0].length? 5 array[0].length? 3 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 6
  • 7. Declaring, Creating, and Initializing Using Shorthand Notations You can also use an array initializer to declare, create and initialize a two-dimensional array. For example, int[][] array = { int[][] array = new int[4][3]; {1, 2, 3}, array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; {4, 5, 6}, Same as array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; {7, 8, 9}, array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; {10, 11, 12} array[3][0] = 10; array[3][1] = 11; array[3][2] = 12; }; Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 7
  • 8. Lengths of Two-dimensional Arrays int[][] x = new int[3][4]; x x[0][0] x[0][1] x[0][2] x[0][3] x[0].length is 4 x[0] x[1] x[1][0] x[1][1] x[1][2] x[1][3] x[1].length is 4 x[2] x[2][0] x[2][1] x[2][2] x[2][3] x[2].length is 4 x.length is 3 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 8
  • 9. Lengths of Two-dimensional Arrays, cont. int[][] array = { array.length {1, 2, 3}, array[0].length {4, 5, 6}, array[1].length {7, 8, 9}, array[2].length {10, 11, 12} array[3].length }; array[4].length ArrayIndexOutOfBoundsException Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 9
  • 10. Ragged Arrays Each row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as a ragged array. For example, int[][] matrix = { {1, 2, 3, 4, 5}, matrix.length is 5 {2, 3, 4, 5}, matrix[0].length is 5 matrix[1].length is 4 {3, 4, 5}, matrix[2].length is 3 {4, 5}, matrix[3].length is 2 {5} matrix[4].length is 1 }; Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 10
  • 11. Ragged Arrays, cont. int[][] triangleArray = { 1 2 3 4 5 {1, 2, 3, 4, 5}, {2, 3, 4, 5}, 2 3 4 5 {3, 4, 5}, {4, 5}, 3 4 5 {5} }; 4 5 5 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 11
  • 12. Processing Two-Dimensional Arrays See the examples in the text. 1. (Initializing arrays with input values) 2. (Printing arrays) 3. (Summing all elements) 4. (Summing all elements by column) 5. (Which row has the largest sum) 6. (Finding the smallest index of the largest element) 7. (Random shuffling) Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 12
  • 13. Initializing arrays with input values java.util.Scanner input = new Scanner(System.in); System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns: "); for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { matrix[row][column] = input.nextInt(); } } Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 13
  • 14. Initializing arrays with random values for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { matrix[row][column] = (int)(Math.random() * 100); } } Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 14
  • 15. Printing arrays for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { System.out.print(matrix[row][column] + " "); } System.out.println(); } Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 15
  • 16. Summing all elements int total = 0; for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { total += matrix[row][column]; } } Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 16
  • 17. Summing elements by column for (int column = 0; column < matrix[0].length; column++) { int total = 0; for (int row = 0; row < matrix.length; row++) total += matrix[row][column]; System.out.println("Sum for column " + column + " is " + total); } Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 17
  • 18. Random shuffling for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { int i1 = (int)(Math.random() * matrix.length); int j1 = (int)(Math.random() * matrix[i].length); // Swap matrix[i][j] with matrix[i1][j1] int temp = matrix[i][j]; matrix[i][j] = matrix[i1][j1]; matrix[i1][j1] = temp; } } Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 18
  • 19. Passing Tow-Dimensional Arrays to Methods PassTwoDimensionalArray Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 19
  • 20. Problem: Grading Multiple- Choice Test  Objective: write a Students’ Answers to the Questions: 0 1 2 3 4 5 6 7 8 9 program that grades Student 0 A B A C C D E E A D multiple-choice test. Student 1 D B A B C A E E A D Student 2 E D D A C B E E A D Student 3 C B A E D C E E A D Key to the Questions: Student 4 A B D C C D E E A D 0 1 2 3 4 5 6 7 8 9 Student 5 B B E C C D E E A D Student 6 B B A C C D E E A D Key D B D C C D A E A D Student 7 E B E C C D E E A D GradeExam Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 20
  • 21. Problem: Finding Two Points Nearest to Each Other x y 0 -1 3 (-1, 3) (3, 3) 1 -1 -1 2 1 1 (4, 2) (1, 1) 3 2 0.5 4 2 -1 (2, 0.5) 5 3 3 (4, -0.5) 6 4 2 (-1, -1) (2, -1) 7 4 -0.5 FindNearestPoints Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 21
  • 22. What is Sudoku? 5 3 7 6 1 9 5 9 8 6 8 6 3 4 8 3 1 7 2 6 6 4 1 9 5 8 7 9 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 22
  • 23. Every row contains the numbers 1 to 9 5 3 7 5 3 4 6 7 8 9 1 2 6 1 9 5 6 7 2 1 9 5 3 4 8 9 8 6 1 9 8 3 4 2 5 6 7 8 6 3 8 5 9 7 6 1 4 2 3 4 8 3 1 4 2 6 8 5 3 7 9 1 7 2 6 7 1 3 9 2 4 8 5 6 6 9 6 1 5 3 7 2 8 4 4 1 9 5 2 8 7 4 1 9 6 3 5 8 7 9 3 4 5 2 8 6 1 7 9 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 23
  • 24. Every column contains the numbers 1 to 9 5 3 7 5 3 4 6 7 8 9 1 2 6 1 9 5 6 7 2 1 9 5 3 4 8 9 8 6 1 9 8 3 4 2 5 6 7 8 6 3 8 5 9 7 6 1 4 2 3 4 8 3 1 4 2 6 8 5 3 7 9 1 7 2 6 7 1 3 9 2 4 8 5 6 6 9 6 1 5 3 7 2 8 4 4 1 9 5 2 8 7 4 1 9 6 3 5 8 7 9 3 4 5 2 8 6 1 7 9 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 24
  • 25. Every 3×3 box contains the numbers 1 to 9 5 3 7 5 3 4 6 7 8 9 1 2 6 1 9 5 6 7 2 1 9 5 3 4 8 9 8 6 1 9 8 3 4 2 5 6 7 8 6 3 8 5 9 7 6 1 4 2 3 4 8 3 1 4 2 6 8 5 3 7 9 1 7 2 6 7 1 3 9 2 4 8 5 6 6 9 6 1 5 3 7 2 8 4 4 1 9 5 2 8 7 4 1 9 6 3 5 8 7 9 3 4 5 2 8 6 1 7 9 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 25
  • 26. Checking Whether a Solution Is Correct 5 3 7 5 3 4 6 7 8 9 1 2 6 1 9 5 6 7 2 1 9 5 3 4 8 9 8 6 1 9 8 3 4 2 5 6 7 8 6 3 8 5 9 7 6 1 4 2 3 4 8 3 1 4 2 6 8 5 3 7 9 1 7 2 6 7 1 3 9 2 4 8 5 6 6 9 6 1 5 3 7 2 8 4 4 1 9 5 2 8 7 4 1 9 6 3 5 8 7 9 3 4 5 2 8 6 1 7 9 CheckSudokuSolution Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 26
  • 27. Multidimensional Arrays Occasionally, you will need to represent n- dimensional data structures. In Java, you can create n-dimensional arrays for any integer n. The way to declare two-dimensional array variables and create two-dimensional arrays can be generalized to declare n-dimensional array variables and create n-dimensional arrays for n >= 3. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 27
  • 28. Multidimensional Arrays double[][][] scores = { {{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}}, {{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}}, {{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}}, {{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}}, {{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}}, {{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}}}; Which student Which exam Multiple-choice or essay scores[ i ] [ j ] [ k ] Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 28
  • 29. Problem: Calculating Total Scores  Objective: write a program that calculates the total score for students in a class. Suppose the scores are stored in a three- dimensional array named scores. The first index in scores refers to a student, the second refers to an exam, and the third refers to the part of the exam. Suppose there are 7 students, 5 exams, and each exam has two parts--the multiple-choice part and the programming part. So, scores[i][j][0] represents the score on the multiple-choice part for the i’s student on the j’s exam. Your program displays the total score for each student. TotalScore Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 29
  • 30. Problem: Weather Information  Suppose a meteorology station records the temperature and humidity at each hour of every day and stores the data for the past ten days in a text file named weather.txt. Each line of the file consists of four numbers that indicate the day, hour, temperature, and humidity. Your task is to write a program that calculates the average daily temperature and humidity for the 10 days. 1 1 76.4 0.92 10 24 98.7 0.74 1 2 77.7 0.93 1 2 77.7 0.93 ... ... 10 23 97.7 0.71 10 23 97.7 0.71 Weather 10 24 98.7 0.74 1 1 76.4 0.92 (b) (a) Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 30
  • 31. Problem: Guessing Birthday  Listing3.8, GuessBirthday.java, gives a program that guesses a birthday. The program can be simplified by storing the numbers in five sets in a three-dimensional array, and it prompts the user for the answers using a loop, as shown in Listing 7.6. The sample run of the program can be the same as shown in Listing 3.8. GuessBirthdayUsingArray Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 31