java 如何使方块自适应,如何在Java中创建魔术方块?

我的任务是编写一个询问用户输入的程序,该方法将返回输入是否形成幻方.不管我进入控制台什么,程序都会返回我输入了一个魔方.我想念什么?

幻方定义:如果行,列和对角线的总和相同,则二维数组就是幻方.

here is the Code:

public class MagicSquares {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

ArrayList ints = new ArrayList();

int current = 0;

do{

System.out.print("Enter an int. Enter -1 when done>");

current = Integer.parseInt(in.nextLine());

}while(current != -1);

int numInputs = ints.size();

int square = (int) Math.sqrt(numInputs);

if(square*square == numInputs){

int[][] intSquare = new int[square][square];

int x = 0;

while(x < numInputs){

for(int y = 0; y < square; ++y){

for(int z = 0; z < square; ++z){

intSquare[y][z] = ints.get(x);

++x;

}

}

}

if(isMagicSquare(intSquare)){

System.out.println("You entered a magic square");

}else{

System.out.println("You did not enter a magic square");

}

}else{

System.out.println("You did not enter a magic square. " +

"You did not even enter a square...");

}

}

private static Boolean isMagicSquare(int[][] array){

int side = array.length;

int magicNum = 0;

for(int x = 0; x < side; ++x){

magicNum =+ array[0][x];

}

int sumX = 0;

int sumY = 0;

int sumD = 0;

for(int x = 0; x > side; ++x){

for (int y = 0; y < side; ++y){

sumX =+ array[x][y];

sumY =+ array[y][x];

}

sumD =+ array[x][x];

if(sumX != magicNum || sumY != magicNum || sumD != magicNum){

return false;

}

}

return true;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值