整齊的二維數組
import java.util.Random; public class a2d { public static void main(String[] args) { var rand = new Random(); int[][] scores = new int[3][5]; for (int i = 0; i < scores.length; ++i) //遍歷賦值 { for (int j = 0; j < scores[i].length; ++j) { scores[i][j] = 60 + rand.nextInt(41); //取[60, 100]之間的隨機數 } } for (int[] row : scores) //輸出數組元素 { for (int score: row) { System.out.printf("%3d", score); } System.out.println(); } } }
ragged array的創建與初始化,遍歷
import java.util.Random; public class a2d { public static void main(String[] args) { var rand = new Random(); //注意學習創建二維ragged array方法 // 方法一: // int[][] scores = new int[3][]; // scores[0] = new int[4]; // scores[1] = new int[6]; // scores[2] = new int[9]; //方法二: int[][] scores = new int[][] { new int[4], new int[6], new int[9] }; int num = 0; //統計成績的個數,用於后面的計算平均數 for (int i = 0; i < scores.length; ++i) //遍歷賦值 { num += scores[i].length; for (int j = 0; j < scores[i].length; ++j) { scores[i][j] = 60 + rand.nextInt(41); //取[60, 100]之間的隨機數 } } int sum = 0; for (int[] row : scores) //輸出數組元素 { for (int score: row) { System.out.printf("%3d", score); sum += score; } System.out.println(); } System.out.println("sum = " + sum); System.out.println("num = " + num); System.out.println("average = " + (sum + .0) / num); } }