[JAVA]二维数组的创建,初始化,遍历输出
整齐的二维数组
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); } }