Question
JAVA ONLY Magic Square Class Write a program to test whether a square is a 3x3 magic square. A magic square is a grid with
JAVA ONLY
Magic Square Class
Write a program to test whether a square is a 3x3 magic square. A magic square is a grid with 3 rows and 3 columns, like the figure below. A magic square has both of the following properties:
the grid contains only the numbers 1 through 9
the sum of each row, each column, and each diagonal all add up to the same number
Notes:
I have provided the start to the program, which creates and displays the square.
MagicSquare.java
public class MagicSquare {
public static void main(String[] args) {
int[][] magicSquare = { {4,9,2}, {3,5,7}, {8,1,6} };
printSquare(magicSquare);
System.out.println("Magic Square? " +
isMagic(magicSquare));
}
public static boolean isMagic(int[][] square) {
// YOUR CODE HERE
return false;
}
public static void printSquare(int[][] square) {
for(int rows=0; rows
for(int cols=0; cols
cols++) {
System.out.print(square[rows][cols] + "
");
}
System.out.println();
}
}
}
You will complete the missing method: isMagic.
You should try different test values to make sure your program works properly.
Your program only has to work for 3x3 squares. It does not need to work more generally for other-sized magic squares.
If you are going to hard-code in positions, for full credit, use constants instead of numbers to improve readability.
For example, square[1][2] isn't as clear as square[MIDDLE_ROW][RIGHT_COL].
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started