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

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

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;
}



}

最佳答案

您没有保存输入的内容,因此将0x0正方形传递给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;
}

关于java - 如何在Java中创建魔术方块?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36102091/

10-09 09:42