随笔 - 3  文章 - 11  trackbacks - 0
<2007年2月>
28293031123
45678910
11121314151617
18192021222324
25262728123
45678910

常用链接

留言簿(1)

随笔档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜

public class trigon2{
   public static void main(String[] args){
      int[][] triarray=new int[10][];
      for(int i=0;i<triarray.length;i++){
         triarray[i]=new int[++i];
      }
      int k=0;
      for(int i=0;i<triarray.length;i++){
         for(int j=0;j<triarray[i].length;j++){
            j=0;
            triarray[i][j]=++k;
            System.out.println(triarray[i][j]);
         }
      }
   }
}
//运行后,抛出异常:

//Exception in thread "main" java.lang.NullPointerException
//        at trigon2.main(trigon2.java:9)
posted on 2007-02-24 22:34 JIM.WU 阅读(441) 评论(5)  编辑  收藏

FeedBack:
# re: 为什么这段程序编译成功,但运行抛出异常? 2007-02-24 23:20 喜来乐哈哈
如果我没猜错的话,你想做的是

public class trigon2{
public static void main(String[] args){
int[][] triarray=new int[10][];
for(int i=0;i<triarray.length;i++){
triarray[i]=new int[++i];
.....

把这里triarray[i]=new int[++i];改成triarray[i]=new int[i+1];


但是这是个无限循环,因为
for(int i=0;i<triarray.length;i++){
for(int j=0;j<triarray[i].length;j++){
j=0;
triarray[i][j]=++k;
System.out.println(triarray[i][j]);
}
}
在内循环你每次又把j=0, j<triarray[i].length当然一直是true了。

至于你看到的
//Exception in thread "main" java.lang.NullPointerException
// at trigon2.main(trigon2.java:9)
异常,是因为在第一个for循环里,你只初始化了triarray[0],triarray[2],...
triarray[1],triarray[3]都还没有被初始化,当然会有NullPointerException。



  回复  更多评论
  
# re: 为什么这段程序编译成功,但运行抛出异常? 2007-02-24 23:51 JIM.WU
@喜来乐哈哈
呵呵。。。。谢谢啦,不过JDK6.0是默认初始化的吧,我试了将++i,改为i+1问题解决,不过是一个无限循环的结果。我本来想要下面的结果,在C里面做很容易,在JAVA里面不知道怎么弄。
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
...........................  回复  更多评论
  
# re: 为什么这段程序编译成功,但运行抛出异常? 2007-02-25 00:02 喜来乐哈哈
默认初始化也只能初始化为null。

用下面的代码就行了,我想不会比C要复杂。

public static void main(String[] args) {
int[][] triarray = new int[10][];
for (int i = 0; i < triarray.length; i++) {
triarray[i] = new int[i + 1];
}
for (int i = 0, k = 1; i < triarray.length; i++) {
for (int j = 0; j < triarray[i].length; j++) {
triarray[i][j] = k++;
}
}
for (int i = 0; i < triarray.length; i++) {
for (int j = 0; j < triarray[i].length; j++) {
System.out.printf("%2d ", triarray[i][j]);
}
System.out.println();
}
}  回复  更多评论
  
# re: 为什么这段程序编译成功,但运行抛出异常? 2007-02-25 00:15 JIM.WU
@喜来乐哈哈
呵呵。。。。谢谢!!
那么下面的程序问题又在哪里呢??
public class trigon{
public static void main(String[] args){
int[][] triarray=new int[10][];
int i=0,j=0;
for(int[] triarray2:triarray){
triarray2=new int[++i];
}

for(int[] triarray2:triarray){
for(int tri:triarray2){
triarray2[j++]=j+1;
System.out.println(triarray2+"");
}
System.out.println("");
}
}
}  回复  更多评论
  
# re: 为什么这段程序编译成功,但运行抛出异常? 2007-02-25 00:38 喜来乐哈哈
运行这个你就知道了

public static void main(String[] args) {
int[][] triarray = new int[10][];
int i = 0, j = 0;
for (int[] triarray2 : triarray) {
triarray2 = new int[++i];
}

for (int[] triarray2 : triarray) {
System.out.println(triarray2);
}
}

  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: