我想对魔术广场进行编程,其中可以利用数组,但是当我要运行它时,它显示Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at MagicSquare.main(MagicSquare.java:6)
我该怎么办?它会显示
4 9 2 7 1 6
3 5 7 not 3 5 7
8 1 6 4 9 2
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int n = Integer.parseInt(args[3]);
if (n % 2 == 0) throw new RuntimeException("n must be odd");
int[][] magic = new int[n][n];
int row = n-1;
int col = n/2;
magic[row][col] = 1;
for (int i = 2; i <= n*n; i++) {
if (magic[(row + 1) % n][(col + 1) % n] == 0) {
row = (row + 1) % n;
col = (col + 1) % n;
}
else {
row = (row - 1 + n) % n;
}
magic[row][col] = i;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (magic[i][j] < 10) System.out.print(" ");
if (magic[i][j] < 100) System.out.print(" ");
System.out.print(magic[i][j] + " ");
}
System.out.println();
}
}
我还应该从该程序中添加或删除什么?
答案 0 :(得分:0)
根据您的程序,运行时需要提供4个参数。例如:如果类名是 Test :
java Test 1 1 1 3
结果:
4 9 2
3 5 7
8 1 6