2011-11-26 123 views
-1

我有一个这样的阵列:阵列2尺寸环

A =

10 11 12 13 14 15 16 0 

17 18 19 20 21 0 0 0 

22 23 24 25 26 27 28 0 

然后我想变换阵列AB看起来像这样的

B =

10 11 12 13 14 

15 16 0 0 0 

17 18 19 20 21 

22 23 24 25 26 

27 28 0 0 0 

以下是我所做的:

public class tesMapping { 

    static int a [][]= new int [][]{{10,11,12,13,14,15,16,0}, 
          {17,18,19,20,21,0,0,0}, 
          {22,23,24,25,26,27,28,0}}; 
    static int b [][]=new int [5][5]; 
    static int j=0; 

    public static void main (String args[]){ 
     for (int i=0;i<5;i++){ 
      for (j=0;j<5;j++) 
       b[i][j]=a[i][j]; 
      int k=5; 
      for (k=5;k<8;k++){ 
      if (a[i][k]!=0){ 
       i++; 
       b[i][j]=a[i][k];   
      } 
     } 
    } 
}} 

该程序仍然错误,真的我不知道了,有人可以帮我吗?

+3

什么是错误? –

+0

错误是ArrayIndexOutOfBoundsException:5 –

+0

它发生在哪里? –

回答

0

您阵列大小不匹配,您增加i超出b的大小。 重新考虑使用变量。尝试使用四个变量:srcXsrcY,dstX,dstY。 然后将增量为dstX/dstY(无论您想要用于行)只有两次:两个内部循环之间和外部循环结束时,以及匹配的src_

1
public static void main(String args[]) { 
    int posBx = 0, posBy = 0; 

    for (int posAx = 0; posAx < a.length; posAx++) { 
     for (int posAy = 0; posAy < a[posAx].length; posAy++) { 

      if (posBy == b[posBx].length) { 
       posBy = 0; 
       posBx++; 
      } 
      if (posBx == b.length) { 
       posBx = 0; 
       posBy++; 
      } 
      b[posBx][posBy++] = a[posAx][posAy]; 

     } 

    } 
} 

的则为a.length < b.length个

0

如果你把静态INT A,B和j你的方法中(下降静态的话),你可以调试你的程序,看看你的变量。我一直试图解决它5分钟,我发现了几个小错误。尝试调试它,如果再次卡住,请告诉我们。