Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Problem from the Java book: \"Big Java, 4th Edition, Cay Horstman\" PROBLEM STAT

ID: 3635040 • Letter: P

Question

Problem from the Java book: "Big Java, 4th Edition, Cay Horstman"

PROBLEM STATEMENT

An n × n matrix that is filled with the numbers 1, 2, 3, … , n2 is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value.
For example,

16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1

You are to write programs that reads in n2 values from the keyboard and tests whether they form a magic square when arranged as a square matrix.

Program Organization Requirements:

Functional Class: Square.java.

-Declare an ArrayList attribute, numbers, to store user input data.

-Declare a two-dimensional int array attribute, square, to put user input into a
square.

-Create a method
public void add(int i) to add a number to the ArrayList numbers.

-Create a method
public booleaqn isMagic() to determine if the square is a magic square. It returns true if a magic square, false otherwise.

-This method should tests
1. Did the user enter n2 numbers for some n? (Eg., 4, 9, 16, 25, …)
2. Do each of the numbers 1, 2, … , n2 occur exactly once in the user input?
3. When the numbers are put into a square, are the sum of the rows, columns, and diagonals equal to each other?

If the size of the input is a square, test whether all numbers between 1 and n2 are present. Then compute the row, column, and diagonal sums to test for a magic square.

-You can add more attributes and/or methods as you need.
-You cannot use Scanner, JOptionPane and System.out,print(in) in this functional class


Test Class: TestMagicSquare.java(This class would have the main method in it)

-Prompt user for a sequence of integers.
-Use Scanner or JOptionPane class.
-Validate user input for int values.
-Use the add(i) method of the Square to add each number to the ArrayList.
-Check if the user input makes a square. If not, stop the program.
-If the numbers make a square, test for uniqueness. If there are any duplicate numbers, stop the program.
-Then call isMagic() method if it is a magic square.

Explanation / Answer

public class MagicSquares { private String [] [] square; private static final int ROWS = 4; private static final int COLUMNS = 4; /** * Constructs an empty square. */ public MagicSquares() { square = new String [ROWS][COLUMNS]; //fill with spaces for (int i = 0; i
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote