how to create magic square in java?

前端 未结 2 1172
甜味超标
甜味超标 2021-01-22 09:41

my task is to write a program that ask user for an input and the method will return whether or not the input forms a magic square. No matter what I enter into the console, the p

2条回答
  •  攒了一身酷
    2021-01-22 10:02

    • You didn't save what is entered, so 0x0 square is passed to isMagicSquare().
    • The implementation of isMagicSquare() is wrong in many points.
      • The condition x > side should be x < side.
      • You have to check sumD only after is calculation is finished.
      • You have to initialize sumX and sumY before calculating them.
      • You should use += instead of =+ to calculate the sum.

    To correct:

    Make the code save the input

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

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

提交回复
热议问题