小编典典

如何在Java中创建魔术方块?

java

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

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

here is the Code:


    public class MagicSquares {


public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    ArrayList<Integer> ints = new ArrayList<Integer>();
    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;
}



}

阅读 251

收藏
2020-11-26

共1个答案

小编典典

  • 您没有保存输入的内容,因此将0x0 square传递给isMagicSquare()
  • isMagicSquare()许多方面的实现是错误的。
    • 条件x > side应该是x < side
    • sumD只需要在计算完成后检查即可。
    • 您必须先进行初始化sumXsumY然后再计算它们。
    • 您应该使用+=而不是=+来计算总和。

纠正:

使代码保存输入

do{
    System.out.print("Enter an int. Enter -1 when done>");
    current = Integer.parseInt(in.nextLine());
    if (current != -1) ints.add(current); // add this line to the loop to read the input
}while(current != -1);

和正确的isMagicSquare()

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 sumD = 0;
    for(int x = 0; x < side; ++x){
        int sumX = 0;
        int sumY = 0;
        for (int y = 0; y < side; ++y){
            sumX += array[x][y];
            sumY += array[y][x];
        }
        sumD =+ array[x][x];
        if(sumX != magicNum  || sumY != magicNum){
            return false;
        }
    }
    return sumD == magicNum;
}
2020-11-26