数组
1、一维数组
int[] ns = { 1, 4, 9, 16, 25 }; for (int i=0;i<ns.length;i++){ sum = sum + ns[i]; } System.out.printf("数组加和为%d",sum); // 遍历数组获取数组的每个值 for (int one : ns){ System.out.println(one); } // 倒序输出数组的每个元素 for (int i=ns.length-1;i>-1;i--){ System.out.println(ns[i]); } // 使用for each 实现数组元素加和 for (int one :ns){ sum = sum + one; } System.out.printf("数组元素和为%d",sum);
2、二维数组
// 二维数组 int[][] ns2 = {{1,2,3},{4,5,6},{7,8,9} }; System.out.println(ns2.length); int[] arr0 = ns2[0]; System.out.println(Arrays.toString(arr0)); System.out.println(ns2[0][0]); for (int[] arr:ns2){ for (int one:arr){ System.out.print(one); System.out.print(", "); } System.out.println(); } // java内置标准库打印二维数据Arrays.deepToString() System.out.println(Arrays.deepToString(ns2));
3、三维数组
// 三维数组 int[][][] ns3 = { { {1,2,3}, {4,5,6} }, { {'a','b','c'}, {'d','e','f'} } }; System.out.println(ns3[0][1][0]);
小练习:
// 二维数据练习 // 用二维数组表示的学生成绩: int[][] scores = { { 82, 90, 91 }, { 68, 72, 64 }, { 95, 91, 89 }, { 67, 52, 60 }, { 79, 81, 85 }, }; double sumAverage = 0; for (int[] arr:scores){ int sum = 0; for (int store:arr){ sum = sum + store; } sumAverage = sumAverage + sum / 3.0; } double average = 0; average = sumAverage / scores.length; System.out.println(average); if (Math.abs(average - 77.733333) < 0.000001) { System.out.println("测试成功"); } else { System.out.println("测试失败"); }
参考:https://www.liaoxuefeng.com/wiki/1252599548343744/1259544232593792#0