3

I have written this program to create a list, then use the list to populate an array. The method magicCheck then checks to see if the matrix is a magic square. I initially wrote it to be a defined matrix of size 4x4. When I did that, everything worked fine. Now I want to let the user decide the size of the array (nxn). After adding the code to prompt the user for n, and creating the matrix based on nxn rather than 4x4, my printMatrix method has stopped working.

When I run the program as is, and enter n=2, first=2, diff=2, this is the output I get: "Enter size of array (in form nxn), n: 4 Enter first and diff : 2 2

It is not a magic square."

Can anyone tell me why printMatrix is no longer working? Also, I know that my magicCheck method is sloppy with the loops and I'm sure there are better ways to handle it, but I'm still very new and piecing it together any way I can to get it to work. Please be gentle :]

Here is my code:

import java.util.*;

public class MagicSquare 
{
static int row, col, n;
static final int rows = n;
static final int columns = n;
static final int listSize = (n*2);
static Scanner console = new Scanner (System.in);

public static void createArithmeticSeq(int [] list)
{   
    //prompt user for array size
    System.out.println("Enter size of array (in form nxn), n:");
    n = console.nextInt();
    int first; 
    int diff;
    //prompt user for first and diff
    System.out.println("Enter first and diff : ");
    first = console.nextInt();
    diff  = console.nextInt();
    //process to create list of 16 elements 
    for (int i=0; i<listSize; i++)
    {
        list[i]=first+i*diff;
    }
}

public static void matricize (int [] list, int [][] matrix)
{
    int i = 0;
//loop through each row
    for (row=0; row<matrix.length; row++)
    {
    //loop through each column
        for (col=0; col<matrix[row].length; col++)
        {
        //populate matrix with values from list
        matrix[row][col] = list[i++];
        }
     }
}
public static void printMatrix(int [][] matrix)
{

    for (row=0; row < matrix.length; row++)
    {
        for (col=0; col < matrix[row].length; col++)
            System.out.printf("%2d" + " ", matrix[row][col]);

        System.out.println("\n");
    }
}

public static void reverseDiagonal(int [] [] matrix)
{ 
    int temp;
    for (row=0; row<matrix.length / 2; row++)
    {
        temp = matrix[row][row];
        matrix[row][row] = 
            matrix[matrix.length - 1 - row] [matrix.length - 1 - row];
        matrix[matrix.length - 1 - row][matrix.length - 1 - row] = temp;
    }
    for (row=0; row<matrix.length / 2; row++)
    {
        temp = matrix[row][matrix.length - 1 - row];
        matrix[row][matrix.length - 1 - row] = 
            matrix[matrix.length - 1 - row][row];
        matrix[matrix.length - 1 - row][row] = temp;
    }
}

public static void magicCheck(int [] list, int [] [] matrix)
{
    int sum=0, sumRow=0, sumCol=0, sumDiag1=0, sumDiag2=0, magicNumber=0;

    for(int i=0; i<listSize; i++)
    {
        sum += list[i]; 
        magicNumber = sum /= 4;

    for(row=0; row<matrix.length; row++)
    {
            //sum each row, then compare to magicNumber
        for(col=0; col<matrix[row].length; col++)
        sumRow = sumRow + matrix[row][col];
        while (sumRow == magicNumber)
        {
            for(col=0; col<matrix.length; col++)
            {
                for(row=0; row<matrix[col].length; row++)
                {
                sumCol = sumCol + matrix[row][col];
                    while (sumCol == magicNumber)
                    {
                    sumDiag1 = matrix[0][0]+matrix[1][1]+matrix[2][2]+matrix[3][3];
                        while (sumDiag1 == magicNumber)
                        {
                        sumDiag2 = matrix[3][0]+matrix[2][1]+matrix[1][2]
                        +matrix[0][3];
                            while(sumDiag2 == magicNumber)
                            System.out.println("It is a magic square.");
                        }
                    }
                }
            }
        }
    }
    }
            System.out.println("It is not a magic square.");

}

public static void main (String [] args)
{
    int [] list = new int [listSize];
    int [] [] matrix = new int [rows] [columns];
    createArithmeticSeq (list);
    matricize(list, matrix);
    printMatrix(matrix);
    System.out.print("\n");
    reverseDiagonal(matrix);
    printMatrix(matrix);
    magicCheck(list, matrix);   
}

}
woollyMammoth
  • 105
  • 1
  • 2
  • 7
  • magicCheck(...) usese hard coded indexes to check your matrix without checking the dimension before – pad Jun 10 '13 at 19:53

1 Answers1

6

You declare:

static int row, col, n;
static final int rows = n;
static final int columns = n;
static final int listSize = (n*2);

before n is set according to the user-input.
First, remove the final from the declarations.
Second, after you read:

n = console.nextInt();

Do:

rows = n;
columns = n;
...

And last, in your main method, switch the order of the lines:

int [] [] matrix = new int [rows] [columns];
createArithmeticSeq (list);
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • 1
    Not initialized int field in Java defaults to 0, so rows and cols are 0. – Grzegorz Żur Jun 10 '13 at 19:45
  • int [] [] matrix = new int [rows] [columns]; generates an 0x0 Matrix and you will never enter the for-loops. – pad Jun 10 '13 at 19:47
  • Thank you! I've made the changes you suggested. Now, of course, I'm running into an index out of bounds error. I can't figure out why, since my loop still stops at i=listSize (i=0; i – woollyMammoth Jun 10 '13 at 20:07
  • I'm not sure what you're trying to do in `process to create list of 16 elements`. My best advice to you is: use a debugger! – Nir Alfasi Jun 10 '13 at 20:12
  • I've changed it to create a list of n*n elements. I have to create a list of size rows*columns to generate enough elements to populate a matrix of size nxn. For instance, when I originally created a 4x4 matrix, the listSize was 16. I have tried using a debugger, but it's not helping much. I still can't figure out why the index is out of bounds. Would it be helpful if I posted my current code as it's been amended? – woollyMammoth Jun 10 '13 at 20:38
  • Never mind, I've solved this issue. Thank you for your original answer. – woollyMammoth Jun 10 '13 at 21:13