- #1

eechord

- 1

- 0

## Homework Statement

An n by 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.

Write a class that creates a square matrix (as a two-dimensional array) andtests whether it forms a magic square. You need to test two features:

Do each of the numbers 1, 2, … n2 occur exactly once in the user input?

When the numbers are put into a square, are the sums of the rows, columns, and diagonals equal to each other?

Implement the class Square, which you will include the following methods:

constructor method Square(int[][] square) that initializes the instance variable squareArray with the parameter square provided by the runner class. This constructor must also calculate the side length of the square.

public void printSquare(), which will print the contents of the square, with tab characters between the values in each column.

public boolean isFull( ) – returns true if the values 1, 2, … n2 occur exactly once, false otherwise.

public boolean isMagic( ) – returns true if the sum of each row, each column and the two diagonals is the same.

public void loadSquare(), which prompts the user for a value for each row and column in the square.

## Homework Equations

I don't have the runner class with me, but can post it later.

## The Attempt at a Solution

Code:

```
public class Square
{
private int sideLength;
private int [][] squareArray;
public Square (int [][]square)
{
int [][] squareArray= int [][]square; //not sure if i did this constructor right
sideLength= 4;
int [][]squareArray= new int [sideLength][sideLength];
}
public void printSquare ()
{
for (int row=0; row<squareArray.length; r++) //not sure whether to use square or squareArray
{
for (int col=0; col<squareArray[row].length; col++)
{
System.out.print (squareArray [row][col]; //not sure how to put tab characters in between values
}
System.out.println ();
}
public boolean isFull ()
{
for (int r=0; r<squareArray.length;r++
{for (int c=0; c<squareArray[r].length; c++)
{if (for(int r2=1; r2<squareArray.length; r2++)
{for (int c2=1; c2<squareArray.length; c2++)
}
return true;
}
public boolean isMagic ()
{
//how do i test if they're all the same, without comparing them individually?
}
public void loadSquare ()
{
//scanner class?
}
```

Last edited by a moderator: