java 二维数组问题

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
java 二维数组问题
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、5
6、72012-10-05
你的 arr 里面有两个一维数组: {4, 5} 和 {6, 7} ,x 的值依次是这两个一维数组。
x.length 是 x 这个一维数组的元素个数,所以是 2
Java 中没有直接得到二维数组总元素个数的方法,只能自己把每个一维数组的元素个数加起来2012-10-05
mengvlog 阅读 8 次 更新于 2025-07-20 08:56:24 我来答关注问题0
檬味博客在线解答立即免费咨询

Java相关话题

Copyright © 2023 WWW.MENGVLOG.COM - 檬味博客
返回顶部