資料型態 陣列名稱[][]=new 資料型態[列個數][行個數]; //列的個數一定要填
java只有這種記憶體分配方式,c++還有其他方法,像是切割記憶體
例:

讓使用者輸入5個學生的三種成績
import java.util.Scanner; public class MainClass { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int arr[][] = new int[5][3]; //宣告一個陣列,存放5個學生3種成績 for(int i=0; i<5; i++){ //5個學生 System.out.println("請輸入學生" + (i+1) + "的成績"); for (int t=0; t<3; t++){ //3種成績 System.out.print("請輸入成績" + (t+1) + ":"); arr[i][t] = sc.nextInt(); } } for(int i=0; i<5; i++){ //5個學生 for (int t=0; t<3; t++){ //3種成績 System.out.print(arr[i][t] + " "); } System.out.println(); } } }
讓使用者輸入5個學生的三種成績(length)
二維陣列的length,不加index指定 => 儲存許多一維陣列的那個一維陣列的長度; 加上index指定 => 每一格存的一維陣列的長度
import java.util.Scanner; public class MainClass { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int arr[][] = new int[5][3]; //宣告一個陣列,存放5個學生3種成績 for(int i=0; i< arr.length; i++){ //5個學生,改用length來表示陣列長度 System.out.println("請輸入學生" + (i+1) + "的成績"); for (int t=0; t<arr[i].length; t++){ //3種成績,指定arr[i]裡面的一維陣列的長度 System.out.print("請輸入成績" + (t+1) + ":"); arr[i][t] = sc.nextInt(); } } for(int i=0; i<5; i++){ //5個學生 for (int t=0; t<3; t++){ //3種成績 System.out.print(arr[i][t] + " "); } System.out.println(); } } }
限制使用者輸入成績的範圍
import java.util.Scanner; public class MainClass { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int arr[][] = new int[5][3]; for(int i=0; i< arr.length; i++){ System.out.println("請輸入學生" + (i+1) + "的成績"); for (int t=0; t<arr[i].length; t++){ do { System.out.print("請輸入成績" + (t+1) + ":"); arr[i][t] = sc.nextInt(); }while(arr[i][t]<0||arr[i][t]>100); //限制成績輸入範圍 } } for(int i=0; i<5; i++){ for (int t=0; t<3; t++){ System.out.print(arr[i][t] + " "); } System.out.println(); } } }
實作練習
請仿照範例實作一次九九乘法表, 數字必須介於1到9之間,並讓使用者輸入被乘數與乘數,以查表的方式找出兩個數字的乘積。
import java.util.Scanner; public class MainClass { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //建立九九乘法表的結果 int arr[][] = new int[9][9]; for(int i = 0; i<9; i++){ for(int j = 0; j<9; j++){ arr[i][j] = (i+1)*(j+1); } } //使用者輸入兩個數 while(true) { int input1, input2; System.out.print("請輸入乘數:"); input1 = sc.nextInt(); System.out.print("請輸入被乘數:"); input2 = sc.nextInt(); System.out.println(input1 + "*" + input2 + "=" + arr[(input1 - 1)][(input2 - 1)]); } } }

