下面是我做的关于魔方阵的程序,
  可是编译时,总是数组越界。
public class mo{
  public static void main(String args[])
     {
     int i,s,x,y;
     int a[][];
     s=Integer.parseInt(args[0]);
    a=new int[s][s];
     for(x=0;x<s;x++)
       for(y=0;y<s;y++)
       a[x][y]=0;
       x=0;
       y=s/2+1;
      a[x][y]=1;
for(i=2;i<=s*s;i++){
     x--;
     y++;
    if(x<0&&y>s-1)
       {
       x=x+2;
       y=y-2;
       a[x][y]=i;
       }
else if(x<0){
       x=s-1;
       a[x][y]=i;
        }
    else if(y>s-1){
       y=0;
      a[x][y]=i;
     }
    else if(a[x][y]!=0)
       {
       x=x+2;
       y=y-2;
       a[x][y]=i;
       }
    
        }
for(x=0;x<s;x++)
       for(y=0;y<s;y++)
    System.out.println(a[x][y]);
   }
}

解决方案 »

  1.   

    你要输入参数才可以。java mo 5或者按照我的来。不过你这个魔方好象还不行啊。我这里只是改了你的错误。public class mo{
        public static void main(String args[]) {
            int i, s, x, y;
            int a[][];        try {
                s = Integer.parseInt(args[0]);
            } catch (Exception e) {
                s = 5;
            }        a = new int[s][s];
            for (x = 0; x < s; x++)
                for (y = 0; y < s; y++)
                    a[x][y] = 0;
            x = 0;
            y = s / 2 + 1;
            a[x][y] = 1;
            for (i = 2; i <= s * s; i++) {
                x--;
                y++;
                if (x < 0 && y > s - 1) {
                    x = x + 2;
                    y = y - 2;
                    a[x][y] = i;
                } else if (x < 0) {
                    x = s - 1;
                    a[x][y] = i;
                } else if (y > s - 1) {
                    y = 0;
                    a[x][y] = i;
                } else if (a[x][y] != 0) {
                    x = x + 2;
                    y = y - 2;
                    a[x][y] = i;
                }        }
            for (x = 0; x < s; x++)
                for (y = 0; y < s; y++)
                    System.out.println(a[x][y]);
        }
    }
      

  2.   

    你的参数是怎么输入的?呵呵。try{}catch(Exception e){}是为了捕获异常
    因为s=Integer.parseInt(args[0]);
    会抛出DataFormateException.