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

匿名用户

1级

2019-01-09 回答

其实就是魔术方阵。。。

给你写了个比较通用的哈。。

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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值