Here's a simple Java implementation demonstrating the creation of a Square class that meets the specified criteria. The add(int i) method allows adding elements to the matrix, while the isMagic() method performs the checking to determine whether the square is a magic square.
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Square {
private final int[][] matrix;
private final int n;
private int fillCount = 0;
public Square(int n) {
this.n = n;
this.matrix = new int[n][n];
}
public void add(int i) {
int row = fillCount / n;
int col = fillCount % n;
matrix[row][col] = i;
fillCount++;
}
public boolean isMagic() {
// Check if the square is fully filled
if (fillCount != n * n) {
return false;
}
// Check if all numbers from 1 to n^2 are present
Set<Integer> numbers = new HashSet<>();
for (int i = 1; i <= n * n; i++) {
numbers.add(i);
}
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
numbers.remove(matrix[row][col]);
}
}
if (!numbers.isEmpty()) {
return false;
}
int sum = 0;
// Calculate the sum of the first row to set as a reference
for (int i = 0; i < n; i++) {
sum += matrix[0][i];
}
// Check rows and columns sum
for (int i = 0; i < n; i++) {
int rowSum = 0, colSum = 0;
for (int j = 0; j < n; j++) {
rowSum += matrix[i][j];
colSum += matrix[j][i];
}
if (rowSum != sum || colSum != sum) {
return false;
}
}
// Check diagonals sum
int diagSum1 = 0, diagSum2 = 0;
for (int i = 0; i < n; i++) {
diagSum1 += matrix[i][i];
diagSum2 += matrix[i][n - 1 - i];
}
return (diagSum1 == sum) && (diagSum2 == sum);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the size of the square (n for an nxn matrix): ");
int n = scanner.nextInt();
Square square = new Square(n);
System.out.println("Enter the " + n * n + " values (1 to " + n * n + "): ");
for (int i = 0; i < n * n; i++) {
square.add(scanner.nextInt());
}
if (square.isMagic()) {
System.out.println("The square is a magic square.");
} else {
System.out.println("The square is not a magic square.");
}
}
}
To use this class, compile and run it. You will be prompted to enter the size of the square matrix (n), followed by n^2 numbers. Each number needs to be entered one at a time (you can modify the input method as necessary).
This solution assumes that the user will input exactly n^2 numbers and validates whether those inputs form a magic square by checking three conditions as required:
- Whether the square matrix is fully filled.
- Whether each number from 1 to n^2 occurs exactly once.
- Whether the sums of rows, columns, and diagonals are equal.