Java基礎之:二維數組
聲明方式:
int[][] x = {{1},{1,2},{1,2,3}};
int[] x[] = new int[5][]; //通過類似這樣的方式聲明(new int[5][]),得到一個可動态生成的二維數組
int x[][] = new int[5][5];
//等号後面的方式可以與的等号前面的方式任意組合使用
//但這種方式是不正确的:x[1] = {1};
說明:
二維數組就是,在一個一維數組裡面儲存的每個元素都是一個一維數組。
二維數組中儲存的是一維數組在棧空間的位址,這些一維數組又指向堆空間中的位址。
簡單聲明案例:
import java.util.Scanner;
public class MultiArray
{
public static void main(String[] args) {
//建立二維數組
int[][] arr = new int[4][6];//預設元素0
//重新指定值
arr[1][2] = 1;
arr[2][1] = 2;
arr[2][3] = 3;
//周遊二維數組
//說明
//1. arr.length 二維數組中,含有多少個一維數組
for( int i = 0; i < arr.length; i++) {
//2. arr[i].length 傳回 arr[i] 一維數組有多少個元素
for( int j = 0; j < arr[i].length; j++) {
//3. arr[i][j] 表示傳回 第i個一維數組的第j個元素值
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
}
簡單動态生成案例:
import java.util.Scanner;
public class MultiArray2
{
public static void main(String[] args) {
int[][] arr = new int[10][];
for( int i = 0; i < arr.length; i++) {
//配置設定空間,一定要注意這裡需要i+1!!!
arr[i] = new int[i+1];
//周遊指派
for( int j = 0; j < arr[i].length; j++) {
arr[i][j] = i+1;
}
}
//輸出周遊
for( int i = 0; i < arr.length; i++) {
//2. arr[i].length 傳回 arr[i] 一維數組有多少個元素
for( int j = 0; j < arr[i].length; j++) {
//3. arr[i][j] 表示傳回 第i個一維數組的第j個元素值
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
}
簡單應用案例:
列印楊輝三角
import java.util.Scanner;
public class YangHui
{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("請輸入要列印的楊輝三角層數:");
int layer = input.nextInt();
int[][] yh = new int[layer][];
System.out.println();
//仔細思考二維數組的動态生成過程,這裡不需要擔心出現空指針的情況
//首先初始化第一行和第二行 避免下面出現空指針異常
// yh[0] = new int[]{1}; //yh[0] = {1}; 是錯誤的!!
// yh[1] = new int[]{1,1};
//動态生成二維數組,并指派
for(int i = 0;i< layer;i++){ //層數,從第三層開始
yh[i] = new int[i+1]; //生成此層的數組
for (int j = 0;j < yh[i].length;j++ ) // 第n層有n個元素
{
if(j == 0 || j == yh[i].length-1){ //第一個和最後一進制素
yh[i][j] = 1;
}else{
yh[i][j] = yh[i-1][j-1] + yh[i-1][j];
}
}
}
//周遊二維數組進行列印輸出
for(int i = 0;i< layer;i++){
for (int j = 0;j < yh[i].length;j++)
{
System.out.print(yh[i][j]+"\t");
}
System.out.println();
}
}
}
思考題
關于運算順序的思考題:
import java.util.Scanner;
public class Think
{
public static void main(String[] args){
int i = 3;
do{
if(i--%2 == 0){ //清楚這裡的運算順序
System.out.println(i);
break;
}
System.out.println(i);
}while(i>0);
}
}
//答案 : 2 1