二维数组
-
int[][] x,y;
int[][] x, y 表示 x 和 y 都是 int 类型的二维数组。
例如:
int[][] num = new int[10][];
num[0] = new int[1];这里的意思是 num[0][1]; -
int[] x, y[];
int[] x 表示 x 是一个一维的 int 类型数组.y[] 表示 y 是一个二维的数组,每个元素都是一个一维的 int 类型数组。可以将 y[] 看作一个“数组的数组”。
public class Exer01{
public static void main(String[] args){
int[][] num = new int[10][];//动态初始化,内层不指定
for(int i = 0; i < num.length; i++){
//二维数组本质上还是一维数组,
num[i] = new int[i + 1];//可以给上面的二维数组的内层初始化长度
}
}
}
- 杨辉三角
public class Exer01 {
public static void main(String[] args) {
//先确定 杨辉三角的二维数组并初始化,这里内层是变化的,所以
//动态初始化
int[][] yangHui = new int[10][];
//根据 杨辉三角的特征,初始化内层数组,这样把 杨辉 二维数组确定
for (int i = 0; i < yangHui.length; i++) {
yangHui[i] = new int[i + 1];
}
for (int i = 0; i < yangHui.length; i++) {
for (int j = 0; j < yangHui[i].length; j++) {
if (j == 0 || j == yangHui[i].length -1) {//第一列和最后一列是 1
yangHui[i][j] = 1;
}else {
yangHui[i][j] = yangHui[i - 1][j - 1] + yangHui[i - 1][j];
}
System.out.print(yangHui[i][j] + " ");
}
System.out.println();
}
}
}
浙公网安备 33010602011771号