public static void main(String[] args) {// TODO Auto-generated method stubint arr[][] = new int[][] { { 4, 5 }, { 6, 7 } };System.out.println("二维数组中的各个元素是");for (int x[] : arr) {for (int i : x) {if (i == x.length) { //这里x.length返回的是什么?System.out.print(i);} elseSystem.out.print(i + "、");}}}为什么最后我的答案是4、5、6、7、?
if (i == x.length) { //这里x.length返回的是x数组的长度因为i在这里是代表int x[]数组中的元素,不是代表int x[]数组中元素的个数,所以i不会等于x.length,最后的答案就是4、5、6、7、。你的程序我帮你改了一下,你看看吧。(改动的地方见注释)public class DD { public static void main(String[] args) { int arr[][] = new int[][] { { 4, 5 }, { 6, 7 } }; System.out.println("二维数组中的各个元素是"); for (int x[] : arr) { for (int i=0;i<x.length;i++) {//这里for (int i : x) 改成for (int i=0;i<x.length;i++) if (i == x.length-1) { //这里x.length返回的是x数组的长度 System.out.println(x[i]);//这里System.out.print(i);改成System.out.println(x[i]); } else System.out.print(x[i] + "、");//这里System.out.print(i + "、");改成System.out.print(x[i] + "、"); } } }}运行结果:二维数组中的各个元素是4、56、7
你的 arr 里面有两个一维数组: {4, 5} 和 {6, 7} ,x 的值依次是这两个一维数组。x.length 是 x 这个一维数组的元素个数,所以是 2Java 中没有直接得到二维数组总元素个数的方法,只能自己把每个一维数组的元素个数加起来