下面是我做的关于魔方阵的程序,
可是编译时,总是数组越界。
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]);
}
}
可是编译时,总是数组越界。
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]);
}
}
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]);
}
}
因为s=Integer.parseInt(args[0]);
会抛出DataFormateException.