← Back to course
Python 11-12 / Week 11 / Thursday
4/6
Week 11 · Reading Java I

Thursday

Arrays and grids
// Same FieldSim ideas, new syntax: types, braces, classes and arrays
⏱ about 30 min

Thursday: Arrays and Grids

Comet wants to see the Larkspur test field in Java. "Our grid was a list of lists," she says. "Can Java do that?"

Nova projects GridDemo.java beside grid.py. "How can I help?" she asks. "Java has arrays. A 2D array is an array of arrays, so the idea is the same."

Wren counts the curly braces on his clipboard. "What does the evidence say? Do both versions find the same four rocks?"

Comet notices something else. "There is no append anywhere in the Java version."

"Good eye," Nova says. "Let us find out why."

Java arrays

A Java array holds a fixed number of values of one type. After it is made, its length cannot change.

Indexes start at 0, and .length gives the size. Valid indexes run from 0 to one less than the length. Any other index is an error.

// ArrayDemo.java
// An int array of four catalog weights (made-up data from the FieldSim story).
public class ArrayDemo {
    public static void main(String[] args) {
        int[] grams = {42, 18, 65, 7};
        System.out.println(grams.length);
        System.out.println(grams[0]);
        System.out.println(grams[grams.length - 1]);
        grams[1] = 20;
        int sum = 0;
        for (int i = 0; i < grams.length; i++) {
            sum += grams[i];
        }
        System.out.println(sum);
    }
}
TRACE ARRAYDEMO
  • Read the question.
  • Tap your answer.
What does grams.length print?
What does grams[grams.length - 1] print?
grams[1] becomes 20 before the loop. What sum is printed?
4
42
7
134

The field as a 2D array

The grid is the Larkspur test field, made-up data from the FieldSim story. The first index is the row and the second is the column.

// GridDemo.java
// The test field as a 2D array of char, like grid.py.
public class GridDemo {
    public static void main(String[] args) {
        char[][] field = {
            {'.', '.', '*', '.', '.', '#'},
            {'.', '#', '.', '.', '.', '.'},
            {'.', '.', '.', '#', '*', '.'},
            {'*', '.', '.', '.', '.', '.'},
            {'.', '.', '#', '.', '.', '*'}
        };
        int rocks = 0;
        for (int r = 0; r < field.length; r++) {
            for (int c = 0; c < field[r].length; c++) {
                if (field[r][c] == '#') {
                    rocks++;
                }
            }
        }
        System.out.println("Rows: " + field.length);
        System.out.println("Columns: " + field[0].length);
        System.out.println("Rocks: " + rocks);
    }
}
grid.py (Python)GridDemo.java (Java)
self._cells, a list of listschar[][] field, an array of arrays
len(self._cells)field.length
len(self._cells[0])field[0].length
for row in self._cells:for (int r = 0; r < field.length; r++) {
if c == mark:if (field[r][c] == '#') {
total += 1rocks++;
READ THE GRID
  • Read the question.
  • Tap your answer.
What does field.length give?
What is field[2][3]?
Which loop goes across the columns of one row?
Rows: 5
Columns: 6
Rocks: 4
At your computer
1. Type grid_twin.py in your fieldsim folder. It uses your own grid.py and field_data.py.
2. Run it and compare the three lines with GridDemo's output.
3. Add print("Samples:", grid.count("*")) at the end. Predict the number, then run it.
4. Now add print(grid.cell(5, 0)) at the end. Run it and read the error calmly.
5. Delete that last line and run it again.
# grid_twin.py
# The Python twin of GridDemo.java.
from field_data import FIELD
from grid import FieldGrid

grid = FieldGrid(FIELD)
print("Rows:", grid.height())
print("Columns:", grid.width())
print("Rocks:", grid.count("#"))
# grid_twin.py
# The Python twin of GridDemo.java.
from field_data import FIELD
from grid import FieldGrid

grid = FieldGrid(FIELD)
print("Rows:", grid.height())
print("Columns:", grid.width())
print("Rocks:", grid.count("#"))
print("Samples:", grid.count("*"))
print(grid.cell(5, 0))
Rows: 5
Columns: 6
Rocks: 4
Samples: 4
Traceback (most recent call last):
  File "grid_twin.py", line 11, in <module>
    print(grid.cell(5, 0))
          ~~~~~~~~~^^^^^^
  File "grid.py", line 23, in cell
    return self._cells[row][col]
           ~~~~~~~~~~~^^^^^
IndexError: list index out of range
What is the name of this Python error?
StatementTrue or false?
A Java array can grow with append.?
A Java array's indexes start at 0.?
In field[r][c], r is the row.?
For an array of length 6, index 6 is valid.?
WHY THIS EXERCISEAn array's length is fixed, and valid indexes run from 0 to one less than the length.

You read a 2D array in Java and matched it to your own grid, lead programmer. Tomorrow is Trace Friday.

← Wednesday