用Java定义一个三行三列的二维数组,要求每行之和等于每列之和

如题所述

其实就是魔术方阵。。。

给你写了个比较通用的哈。。
public class MagicSquare {

/**
* @param args
*/
//注意只能产生奇数的魔术方阵 偶数的规律不一样
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] square = generateSquare(3);
for(int[] nums : square) {
for(int num : nums) {
System.out.printf("%-4d", num);
}
System.out.println();
}
}

//产生魔术方阵的方法 注意只能是奇数方阵哈 参数count就是你想要产生几阶的
public static int[][] generateSquare(int count) {
int[][] square = new int[count][count];
int row = 0;
int col = count / 2;
square[row][col] = 1;
for(int i = 2; i <= count * count; i++) {
row--;
col--;
if(row < 0) {
row = count - 1;
}
if(col < 0) {
col = count - 1;
}
if(square[row][col] != 0) {
if(row == count - 1) {
row = 0;
} else {
row++;
}
if(col == count - 1) {
col = 0;
} else {
col++;
}
row++;
if(row > count - 1) {
row = 0;
}
}
square[row][col] = i;
}
return square;
}

}
温馨提示:答案为网友推荐,仅供参考
相似回答