Wondrous Square Program in Java | ISC Computer Science

A wondrous square is an N × N matrix that meets the following conditions:

  1. It contains integers from 1 to N2, such that every integer appears only once.
  2. The sum of the integers of every row and column equals 0.5 × N × (N2 + 1).

Example:
INPUT:
N = 3
ENTER MATRIX ELEMENTS:
8 1 6
3 5 7
4 9 2
OUTPUT:
ORIGINAL MATRIX:
8 1 6
3 5 7
4 9 2
IT IS A WONDROUS SQUARE.

Write a Java program to input the value of N from the user where 2 ≤ N ≤ 10. Create N × N matrix. Input the integers to fill this matrix. Now check if this matrix is a wondrous square or not and display a suitable message accordingly.

import java.util.Scanner;
class WondrousSquare{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("N = ");
        int n = Integer.parseInt(in.nextLine());
        if(n < 2 || n > 10){
            System.out.println("INVALID RANGE");
            return;
        }
        int a[][] = new int[n][n];
        boolean isWondrous = true;
        System.out.println("ENTER MATRIX ELEMENTS:");
        for(int i = 0; i < a.length; i++){
            for(int j = 0; j < a.length; j++){
                a[i][j] = Integer.parseInt(in.nextLine());
                if(a[i][j] < 1 || a[i][j] > n * n || duplicates(a, a[i][j]))
                    isWondrous = false;
            }
        }
        int sum = n * (n * n + 1) / 2;
        System.out.println("ORIGINAL MATRIX:");
        for(int i = 0; i < a.length; i++){
            for(int j = 0; j < a.length; j++){
                System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }
        outer1:
        for(int i = 0; i < a.length; i++){
            int rowSum = 0;
            for(int j = 0; j < a.length; j++){
                rowSum += a[i][j];
            }
            if(rowSum != sum){
                isWondrous = false;
                break outer1;
            }
        }
        outer2:
        for(int i = 0; i < a.length; i++){
            int colSum = 0;
            for(int j = 0; j < a.length; j++){
                colSum += a[j][i];
            }
            if(colSum != sum){
                isWondrous = false;
                break outer2;
            }
        }
        if(isWondrous)
            System.out.println("IT IS A WONDROUS SQUARE.");
        else
            System.out.println("IT IS NOT A WONDROUS SQUARE.");
    }
    public static boolean duplicates(int a[][], int elem){
        int count = 0;
        for(int i = 0; i < a.length; i++){
            for(int j = 0; j < a.length; j++){
                if(a[i][j] == elem)
                    count++;
                if(count > 1)
                    return true;
            }
        }
        return false;
    }
}