Create a class called MagicSquare.java. public static void main(String[] args) {
ID: 3829161 • Letter: C
Question
Create a class called MagicSquare.java.
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"));
}
It is your job to write the method isMagicSquare:
public static boolean isMagicSquare(int[][] square) {
// TODO
}
How do you know whether a 2-dimensional array is a magic square?
First of all it needs to be a square. To keep the scope of the lab manageable you may assume that the 2-dimensional arrays passed have the same number of rows and columns and that there is at least one row and one column.
The square is 'magic' if the numbers in each of the rows, columns, and diagonals add up to the same value (see image above)
Recommendation: use private methods tp structure your code.
Explanation / Answer
// MagicSquare.java
import java.util.*;
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)
{
boolean ismagicsquare = true;
for (int i = 0; i < square.length; i++)
{
if (square[i].length != square.length)
{
ismagicsquare = false;
}
}
if (ismagicsquare)
{
int total = 0;
for (int j = 0; j < square.length; j++)
{
total += square[0][j];
}
for (int i = 1; i < square.length; i++)
{
int newtotal = 0;
for (int j = 0; j < square[i].length; j++)
{
newtotal += square[i][j];
}
if (total != newtotal)
{
ismagicsquare = false;
}
}
}
return ismagicsquare;
}
}
/*
output:
The square is a magic square.
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.