2D Arrays
Additional programming style guidelines:
/* * 1. Make sure your program has indentation when is needed. * 2. Please include a comment line about local variables and group them all * together at the top of the program as long as it is not an OOD program. * 3. Never create a new local variable inside a loop! * 4. Have a blank line between different parts of the program */
final int COUNTRIES = 7; final int MEDALS = 3; int[][] counts = new int[COUNTRIES][MEDALS];
or but not both:
int[][] counts = { { 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 1 }, { 0, 1, 1 }, { 1, 1, 0 } };
for (int i = 0; i < COUNTRIES; i++) { // Process the ith row for (int j = 0; j < MEDALS; j++) { // Process the jth column in the ith row System.out.printf("%8d", counts[i][j]); } System.out.println(); // Start a new line at the end of the row }
for (int i = 0; i < counts.length; i++) { for (int j = 0; j < counts[0].length; j++) { System.out.printf("%8d", counts[i][j]); } System.out.println(); }
Accessing the neighboring elements of a 2D array
Adding by rows:
int total = 0; for (int i = 0; i < COUNTRIES; i++) { total = 0; for (int j = 0; j < MEDALS; j++) { total = total + counts[i][j]; } }
Adding by columns:
int total = 0; for (int j = 0; j < MEDALS; j++) { total = 0; for (int i = 0; i < COUNTRIES; i++) { total = total + counts[i][j]; } }
Classwork:
Write a program, MedalsTable_YI.java to produce the following output:
Assignment:
Consider as an example an 8 × 8 array for a board game:
int[][] board = new int[8][8];
BoardGame_YI.java: Using two nested loops, initialize the board using "for" loops so that zeroes and ones alternate, as on a checkerboard. Prompt the user for the size of the "square" 2D array and display the board on the screen.
0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 ... 1 0 1 0 1 0 1 0
Hint: Check whether i + j is even.