我有一个关于 MAGIC SQUARE 的任务:
但我需要重写它。
这是我目前的代码:
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num= input.nextInt();
//Number must be ODD and not less than or equals to one to continue
while((num%2==0)||(num<=1)){
System.out.println("Enter a valid number: ");
num= input.nextInt();
}
int[][] magic = new int[num][num];
int row = num-1;
int col = num/2;
magic[row][col] = 1;
for (int i = 2; i <= num*num; i++) {
if (magic[(row + 1) % num][(col + 1) % num] == 0) {
row = (row + 1) % num;
col = (col + 1) % num;
}
else {
row = (row - 1 + num) % num;
// don't change col
}
magic[row][col] = i;
}
// print results
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
if (magic[i][j] < 10) System.out.print(" "); // for alignment
if (magic[i][j] < 100) System.out.print(" "); // for alignment
System.out.print(magic[i][j] + " ");
}
System.out.println();
}
目前,我的程序输出是:
我的预期/期望输出:
我需要的是起始数字 (1) 位于行 x col 的中上部,然后模式是向上然后向左。