此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
一个数值的网格
- 普通的数组是一行数值。
- 二维数组(2-D array)是一个网格(grid):它有行(row)和列(column),就像一张表格或电子表格。
- 我们用它来表示棋盘、图像、成绩表等等。
创建2维数组
int[][] g = new int[3][4];创建一个有 3 行和 4 列的网格。- 每个格子(cell)一开始都是
0(对于int)。 - 你也可以在
{...}里面直接用值把它填好。
English
public class Main {
public static void main(String[] args) {
int[][] g = new int[3][4]; // 3 rows, 4 columns, all 0
int[][] table = {
{1, 2, 3},
{4, 5, 6}
}; // 2 rows, 3 columns
System.out.println(table[0][2]); // 3
System.out.println(table[1][0]); // 4
}
}
读取和写入一个格子
- 一个格子需要两个下标:
g[row][col]。先行,后列。 - 两个下标都从 0 开始。
g[1][2] = 9;把9存进第1行、第2列。
English
public class Main {
public static void main(String[] args) {
int[][] g = new int[2][2];
g[0][0] = 5;
g[0][1] = 7;
g[1][0] = 9;
g[1][1] = 11;
System.out.println(g[1][0]); // 9
g[1][0] = g[1][0] + 1;
System.out.println(g[1][0]); // 10
}
}
网格有多大?
g.length—— 行的数量。g[0].length—— 第0行里列的数量。- 在 AP CSA 中,每一行的长度都相同,所以
g[0].length就是整个网格的列数。
English
public class Main {
public static void main(String[] args) {
int[][] g = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(g.length); // 2 rows
System.out.println(g[0].length); // 3 columns
}
}
行优先遍历
- 要访问每一个格子,使用一个循环嵌套在另一个循环里面。
- 外层循环选择行
r。内层循环选择列c。 - 这样会先完整地走完第
0行,再走第1行,以此类推。这种顺序叫作行优先(row-major)。
English
public class Main {
public static void main(String[] args) {
int[][] g = {
{1, 2, 3},
{4, 5, 6}
};
int total = 0;
for (int r = 0; r < g.length; r++) {
for (int c = 0; c < g[0].length; c++) {
total = total + g[r][c];
}
}
System.out.println(total); // 21
}
}
常见错误
- 网格索引
grid[row][col]。 grid.length是行数;grid[0].length是列数。
现在轮到你
- 每个任务都已经填好了类的骨架 —— 把你的代码写在 main 里面,或者补全给出的方法。
- 对于完整程序,Run(运行)会编译并执行它。对于方法或类任务,Check answer(检查答案)会使用提供的测试编译您的代码并显示结果。
- 你的代码在服务器上编译并运行,所以第一次运行也很快。
探索
A 2-D array is a grid
A 2-D array is rows × columns; reach a cell with a[row][col].
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Complete sumGrid(int[][] g) so it returns the 总 of every cell in the grid. Use a nested loop with g.length rows and g[0].length columns.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Complete rowSum(int[][] g, int r) so it returns the total of the cells in 行 r only. Loop over the columns of that one row.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
In main, the grid is given. Print each 行 on its own line, with the numbers joined by a single space. For the grid shown, the output is 1 2 3 then 4 5 6. (Build each line in row-major order, then println it.)
点击“运行”查看此处输出。