Ask Question
17 October, 17:53

Write a class called MagicSquare, which contains a single method called check that accepts a two-dimensional array as an argument, and determines whether the array is a Magic Square. Write a class called MagicSquareDemo, which demonstrates the above class/method.

+3
Answers (1)
  1. 17 October, 19:18
    0
    public class MagicSquare {

    public static void main (String[] args) {

    int[][] square = {

    { 8, 11, 14, 1},

    {13, 2, 7,12},

    { 3, 16, 9, 6},

    {10, 5, 4, 15}

    };

    System. out. printf ("The square %s a magic square. %n",

    (isMagicSquare (square) ? "is" : "is not"));

    }

    public static boolean isMagicSquare (int[][] square) {

    if (square. length! = square[0]. length) {

    return false;

    }

    int sum = 0;

    for (int i = 0; i < square[0]. length; + +i) {

    sum + = square[0][i];

    }

    int d1 = 0, d2 = 0;

    for (int i = 0; i < square. length; + +i) {

    int row_sum = 0;

    int col_sum = 0;

    for (int j = 0; j < square[0]. length; + +j) {

    if (i = = j) {

    d1 + = square[i][j];

    }

    if (j = = square. length-i-1) {

    d2 + = square[i][j];

    }

    row_sum + = square[i][j];

    col_sum + = square[j][i];

    }

    if (row_sum! = sum || col_sum! = sum) {

    return false;

    }

    }

    return d1 = = sum && d2 = = sum;

    }

    }
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Write a class called MagicSquare, which contains a single method called check that accepts a two-dimensional array as an argument, and ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers