注册 登录
编程论坛 J2EE论坛

关于java二维数组的问题

zl芊芊zl 发布于 2008-11-06 16:44, 1377 次点击
我写的如下
import *;
public class TestArray {

   public static void main (String[] args) {
       int [][] smallPrime={{2,3},{5,7},{11,13,17}};
       int i=0;int j=0;
       for(i=0;i<3;i++){
       for(j=0;j<3;j++) {
           System.out.println(smallPrime[i][j]);
           }    
       }
       
   }
   
}

输出的结果是这样的
2
3
java.lang.ArrayIndexOutOfBoundsException: 2
    at TestArray.main(TestArray.java:17)
Exception in thread "main"
Process completed.



为什么不输出
2,3,0,5,7,0,11,13,17
C++中默认的是0,Java中呢?
我如果想把我的二维数组输出怎么写呀?谢谢啦
5 回复
#2
cqusnail2008-11-06 17:17
第一维数组只有两个数,你却要输出三个数.

巧妇难为无米之炊啊
#3
freish2008-11-06 17:30
谁告诉你你的数组是3*3的了?!

程序代码:
public class TestArray {
   public static void main (String[] args) {
       int [][] smallPrime={{2,3},{5,7},{11,13,17}};
       System.out.println(smallPrime[0].length);
       System.out.println(smallPrime[1].length);
       System.out.println(smallPrime[2].length);
   }
}


去看看每一维的长度
#4
zl芊芊zl2008-11-07 13:02
[bo][un]freish[/un] 在 2008-11-6 17:30 的发言:[/bo]

谁告诉你你的数组是3*3的了?!

public class TestArray {
   public static void main (String[] args) {
       int [][] smallPrime={{2,3},{5,7},{11,13,17}};
       System.out.println(smallPrime[0].l ...

长度是
2
2
3
那这个数组怎么输出呢
#5
freish2008-11-07 13:28
都知道长度怎么还输不出呢

程序代码:
public class TestArray {
   public static void main (String[] args) {
       int [][] smallPrime={{2,3},{5,7},{11,13,17}};
       for(int i=0;i<smallPrime.length;i++)
           for(int j=0;j<smallPrime[i].length;j++)
               System.out.println(smallPrime[i][j]);
   }
}
#6
zl芊芊zl2008-11-10 14:44
哦知道了
谢谢版主
我刚学的Java,好多地方不懂,叫你见笑啦
嘿嘿
谢谢哈,以后还请多多指教
1