# help with magic squares

• 01-17-2012, 11:43 PM
grandmastertheory
help with magic squares
Code:

```import java.io.*; import java.util.Scanner; public class SquareTest {     public static void main(String[] args) throws FileNotFoundException     {               int size=0;     Scanner inputSize = new Scanner(new File("magicdatasize.txt"));     Scanner inputData = new Scanner(new File("magicData.txt"));         int count=1;  //count which square we're on     size = inputSize.nextInt(); //size of next square       //Expecting -1 at bottom of input file     while (size != -1)         {           //create a new Square of the given size           Square testSquare = new Square(size);         //fill the temp array with values of the square               int[][] temp = new int[size][size];         {             for (int row = 0; row < temp.length; row++)             for (int col = 0; col < temp.length; col ++)             temp[row][col] = inputData.nextInt();                   }               //call its read method to read the values of the square         testSquare.readSquare(temp);//Passing the full array         System.out.println("\n******** Square " + count + " ********");                             //print the square         testSquare.printSquare();                 for(int f=0; f<temp.length; f++)         {             System.out.println("Sum of row " + (f+1) + "is: " + testSquare.sumRow(f));             System.out.println();               }         //print the sums of its rows                     for(int d=0; d<temp.length; d++){                       System.out.println("Sum of column " + (d+1) + ":  " + testSquare.sumCol(d));             System.out.println();                   }                     //print the sums of its columns                     System.out.println("Sum of main diagonal" + testSquare.sumMainDiag());         System.out.println();               //print the sum of the main diagonal             System.out.println("Sum of main diagonal" + testSquare.sumMainDiag());           //print the sum of the other diagonal         System.out.println();                           System.out.println("Sum of other diagonal" + testSquare.sumOtherDiag());         //determine and print whether it is a magic square         if(testSquare.magic()==true)         {             System.out.println("It is a magic square!");                   //get size of next square         size = inputSize.nextInt();         count ++;         }             } } }                                 ^ that is the main method l import java.io.FileNotFoundException;   public class Square   {   boolean magic;       int[][] square;         //--------------------------------------     //create new square of given size     //--------------------------------------     public Square(int size)     {         int[][]Square = new int [size][size];             }       //--------------------------------------     //return the sum of the values in the given row     //--------------------------------------     public int sumRow(int row)     {                         int sumRow=0;         for (int v=0;v<(square.length-1); v++)         {                       sumRow=sumRow+square[row][v];         }                         return sumRow;     }       //--------------------------------------     //return the sum of the values in the given column     //--------------------------------------     public int sumCol(int col)     {                       int sumCol=0;         for (int u=0;u<(square.length-1); u++)             {             int sumcol=0;             sumCol=sumCol+square[u][col];             }                                   return sumCol;                       }                 //--------------------------------------     //return the sum of the values in the main diagonal     //--------------------------------------     public int sumMainDiag()     {       int summain=0;         int c=0;       int r=0;       for(int z=0; r<square.length; z++)       {           summain=summain + square[c][r];           c++;           r++;         }         return summain;         }       //--------------------------------------     //return the sum of the values in the other ("reverse") diagonal     //--------------------------------------     public int sumOtherDiag()     {                 int oth=0;         int x=0;         int y=square.length;         for (int q=0; x<square.length; q++)         {             oth= oth+square[x][y];             x++;             y--;         }                     return oth;       }       //--------------------------------------     //return true if the square is magic (all rows, cols, and diags have     //same sum), false otherwise     //--------------------------------------             public boolean magic()     {                 if ((sumMainDiag())==sumOtherDiag())     {     int sumRow=0;     int sumCol=0;     int row=0;     int col=0;       for(int t =0; t<(square.length); t++)     {       sumRow += square[row][t];     sumCol += square[t][col];       if (sumRow ==sumCol)       {           boolean magic = true;         }             else  {         boolean magic = false;               }           }   } else{                     boolean magic= false;         }         return magic;       }                                   //--------------------------------------     //read info into the square from the standard input.     //--------------------------------------     public void readSquare(int temp[][])     {       int square[][]= temp;                   }          //--------------------------------------     //print the contents of the square, neatly formatted     //--------------------------------------     public void printSquare()     {   ////////  RIGHT AFTER THIS THE VERY NEXT LINE I GET AN ERROR THAT SAYS "JAVA.LANG.NULLPOINTEREXEPTION NULL"          for(int r=0; r<(square.length); r++){                             for(int c=0; c<(square.length); c++)         {         System.out.println(" " + square[r][c]);     }     } } }   //this is THE SQUARE CLASS```

I AM READING FILES AND USING A SCANNER TO BRING THEM INTO THE PROGRAM
• 01-18-2012, 12:42 AM
Fubarable
Re: help with magic squares
I think I speak for all in wishing you much luck with this project. If you have a specific question, feel free to ask it any time you'd like.
• 01-18-2012, 01:06 AM
pbrockway2
Re: help with magic squares
Please format your code when you post it: put [code] at the start of the code and [/code] at the end. That way the code will be readable. You might also want to remove unnecessary space for the same reason.

The way it was it's little wonder your question was missed. (In fact it's a good idea not to put the question into the code - most people prefer to see the code exactly as it was when you ran it. Also the "stack trace" - the thing mentioning the NullPointerException - should be copied and posted in its entirety. Again, programmers tend to be fussy about the details.)

-----

extracted:

Code:

```////////  RIGHT AFTER THIS THE VERY NEXT LINE I GET AN ERROR THAT SAYS "JAVA.LANG.NULLPOINTEREXEPTION NULL"          for(int r=0; r<(square.length); r++){```
NullPointerException means that you were trying to use a variable as if it had a nonnull value when, in fact it was null. Common culprits are the [] operator and the dot operator:

Code:

```int[] arr; arr[42] = 666;    // bad! arr is null String foo; foo.getCharAt(42); // bad! foo is null```
If we look at the line of code in question we see that the villain *must* be square. That's because r is an int, and ints are never "null". Evidently square is null and when you use the dot (dereference) operator, as in square.length, you will get a NullPointerException.

You can check this with System.out.println():

Code:

```System.out.println("About to start the square loop.  square=" + square); for(int r=0; r<(square.length); r++){```
Having given square a fair trial in this fashion you need to decide what to do. In mitigation square will doubtless raise the question of his upbringing and unfortunate past: "I was never properly initialised, your honour!"

So go back through your code to the place where you thought you had given square a decent nonnull value, and find out why that did not, in fact, happen.