Hi,
I got a compile error of incompatible types - lang.object is found but int expected on line 21. But when i put int in front of square, it says .class error:/
P.S. I didn't write everything here, I got some codes from other programs:P
import java.util.ArrayList;
/**
A magic square is an n x n matrix which, if filled with numbers,
the sum of the elements in each row, each column,
and the two diagonal is the same value.
*/
public class Square
{
/**
Construct a Square object.
@param input the list of numbers
*/
public Square(ArrayList input)
{
size = (int) Math.sqrt(input.size());
square = new int[size][size];
for (int i = 0; i < size ; i++)
for (int j = 0; j < size ; j++)
square[i][j] = input.get(i * size + j);
}
/**
Display the contents of the square.
@param the ith row
@param the jth column
@return a string represenation of the square
*/
public String toString(int i, int j)
{
String s = " " + square[i][j];
return s.substring(s.length() - 3, s.length());
}
/**
Search for a number in the square.
@param n the number to search for
@return if the number is found, false otherwise
*/
public boolean found(int n)
{
for (int i = 0; i < size ; i++)
{
for (int j = 0; j < size ; j++)
{
if (square[i][j] == n)
return true;
}
}
return false;
}
/**
Add the numbers in the square.
@param i the row/column to add
@param row determines if a row or column should be added
@return sum the sum of the row/column
*/
public int add(int i, boolean row)
{
int sum = 0;
for (int j = 0; j < size; j++)
{
if (row)
sum = sum + square[i][j];
else
sum = sum + square[j][i];
}
return sum;
}
/**
Find the sum of the diagonal.
@param mainDiagonal determine if it is the main diagonal
@return sum the sum of the diagonal
*/
public int diagonalSum(boolean mainDiagonal)
{
int sum = 0;
for (int i = 0; i < size; i++)
{
int j;
if (mainDiagonal)
j = i;
else
j = size - 1 - i;
sum = sum + square[i][j];
}
return sum;
}
/**
Determine if the square is a magic square.
@return true if square is a magic square, false otherwise
*/
public boolean isMagic()
{
for (int n = 1; n <= size * size; n++)
{
if (!found(n))
return false;
}
int sum = diagonalSum(true);
if (sum != diagonalSum(false))
return false;
for (int i = 0; i < size; i++)
{
if (sum != add(i, true))
return false;
if (sum != add(i, false))
return false;
}
return true;
}
private int[][] square;
private int size;