Background:

An n x n matrix that is filled with the numbers 1, 2, 3, ... n squared 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. Write a program that reads in n squared values from the keyboard and tests whether they form a magic square when arranged as a square matrix. test for three features:

A. Did the user enter nsquared numbers for some n?

B. Do each of the numbers 1, 2, ...nsquared occur exactly once in the user input?

C. When the numbers are put into a square, are the sums 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 nsquared are present. Then compute the row, column, and diagonal sums. Implement a class Square with methods

```
public void add (int i)
public bolean isMagic()
```

Here is what I have so far, not sure how to start the number part??

```
/**
* Write a program that creates a magic 4 x 4 square that is filled with
* numbers if the sum of the elements in each row, column, and in the 2 diagonals
* have the same value.
*
* @author (Todd Higdon)
* @version (CPSC 150-02 3-15-07)
*/
/**
* A 4 x 4 Magic Square.
*/
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 < ROWS; i++)
for (int j = 0; j < COLUMNS; j++)
square [j] = " ";
}
/**
* Sets a field in the square. The field must be unoccupied.
@param i the row index
@param j the column index
@param user the user (n x n)
*/
public void set (int i, int j, String user)
{
if (square [j].equals (" "))
square [j] = user;
}
public String toString()
{
String r = " ";
for (int i = 0; i < ROWS; i++)
{
r = r + "|";
for (int j = 0; j < COLUMNS; j++)
r = r + square[j];
r = r + " |\n";
}
return r;
}
}
TESTER IS:
import java.util.*;
public class MagicSquaresTester
{
public static void main (String[]args)
{
Scanner in = new Scanner(System.in);
String user = "n";
MagicSquares square= new MagicSquares();
boolean done = false;
while (!done)
{
System.out.print (square.toString());
System.out.print(
"Row for " + user + " (-1 to exit): ");
int row = in.nextInt();
if (row <0) done = true;
else
{
System.out.print("Column for " + user + " : ");
int column = in.nextInt();
square.set(row, column, user);
if (user.equals("n"))
user = "n";
}
}
}
}
```

*Edited 3 Years Ago by happygeek*: fixed formatting