# Need Help with Magic Square

• 04-21-2010, 11:25 PM
easybe
Need Help with Magic Square
Hi, I'm new to Java and I am kind of stuck on trying to print out my square, and also I want to make sure I have the correct formatting in my code for SquareTest.java.

Any suggestions are great. Here are the two codes:

Code:

```// **************************************************************** // Square.java // // Define a Square class with methods to create and read in // info for a square matrix and to compute the sum of a row, // a col, either diagonal, and whether it is magic. // // **************************************************************** import java.util.Scanner; public class Square {     int[][] square;     int row, col, sumMainDiag = 0, sumOtherDiag = 0;     boolean magic; //-------------------------------------- // create new square of given size //--------------------------------------   public Square(int size)     {             } //-------------------------------------- // return the sum of the values in the given row //--------------------------------------     public int sumRow(int row)     {         return row;     } //-------------------------------------- //return the sum of the values in the given column //--------------------------------------   public int sumCol(int col)     {         return col;     } //-------------------------------------- // return the sum of the values in the main diagonal //--------------------------------------   public int sumMainDiag()   {         return sumMainDiag;   } //-------------------------------------- //return the sum of the values in the other ("reverse") diagonal //--------------------------------------   public int sumOtherDiag()     {         return sumOtherDiag;     } //-------------------------------------- // return true if the square is magic (all rows, cols, and diags // have same sum), false otherwise //--------------------------------------     public void magic()     {         if (row == col)         if (sumMainDiag == sumOtherDiag)         {         System.out.println("True");         }                   else         {                 System.out.println("False");         }     } //-------------------------------------- // read info into the square from the input stream associated with // the Scanner parameter //--------------------------------------   public void readSquare(Scanner scan)   {       for (int row = 0; row < square.length; row++)       for (int col = 0; col < square.length; col++)       square[row][col] = scan.nextInt();   } //-------------------------------------- // print the contents of the square, neatly formatted //--------------------------------------         public String printSquare()   {     } }```

Code:

``` // **************************************************************** // SquareTest.java // // Uses the Square class to read in square data and tell if // each square is magic. // // **************************************************************** import java.util.Scanner; import java.io.IOException; import java.io.File; public class SquareTest {       public static void main(String[] args) throws IOException       {       Scanner scan = new Scanner(new File("C:\\Users\\Tamika\\Documents\\CS 201 Lab Folder\\Lab Homework\\Homework 4\\Homework 4\\magicData"));     // make sure that the file magicData is in the current directory     int count = 1; //count which square we're on     int size = scan.nextInt(); //size of next square     //Expecting -1 at bottom of input file     while (size != -1)     {         //create a new Square of the given size         Square s = new Square(size);         //call its read method to read the values of the square         System.out.println("\n***** Square " + count + " *****");         //print the square         s.printSquare();         //print the sums of its rows         for (int row = 0; row < size; row++)         {             System.out.println("Sum of row " + row + "is: " + s.sumRow(row));         }             System.out.println();         //print the sums of its columns         for (int col = 0; col < size; col++)         {             System.out.println("Sum of columns " + col + "is: " + s.sumCol(col));         }             System.out.println();           //print the sum of the main diagonal         System.out.println("The sum of the main diagonal is: " + s.sumMainDiag);         System.out.println();       //print the sum of the other diagonal       System.out.println("The sum of the other diagonal is: " + s.sumOtherDiag());       System.out.println();       //determine and print whether it is a magic square       System.out.println("Is it a magic square: " + s.magic);       //get size of next square       size = scan.nextInt();       count++;     }  } }```

THANKS
• 04-21-2010, 11:45 PM
Fubarable
Welcome to the forum. I added code tags to your code to help make it retain its formatting, but then I noticed that much of the code you posted was poorly formatted. I strongly suggest that you edit your post above and replace any unformatted or poorly formatted code with that with decent formatting/indentation. It will make your code much easier to read and thus increase your chances of getting help.

Please post if you don't understand my request, and as always, best of luck!
• 04-22-2010, 12:06 AM
easybe
Quote:

Originally Posted by Fubarable
Welcome to the forum. I added code tags to your code to help make it retain its formatting, but then I noticed that much of the code you posted was poorly formatted. I strongly suggest that you edit your post above and replace any unformatted or poorly formatted code with that with decent formatting/indentation. It will make your code much easier to read and thus increase your chances of getting help.

Please post if you don't understand my request, and as always, best of luck!

I hope this is better formatted for better reading
• 04-22-2010, 12:17 AM
Fubarable
OK, thanks for formatting the code as now it is much easier to read.

On review of this code I am guessing that SquareTest.java was provided to you by your instructor, and that you have created the Square class based on an outline given to you. The class unfortunately has many significant problems, some of which I'd like to discuss:

First off in your Square(int size) constructor should have some code in it: you should be doing something with the size parameter, perhaps initializing the two-dimensional square int array. Have you used new to initialize an array before? If not we can refer you to a decent tutorial: http://java.sun.com/docs/books/tutor...ts/arrays.html

Next off the sumRow(int row) method does nothing but return the row parameter passed into it. Consider re-writing this so that it uses a for loop to sum all of the ints present in the row specified. One of the array's indices will be fixed (it will hold the row number passed as the parameter) and the other will hold the loop index (often "i").

Ditto on the sumCol method -- it does nothing useful and certainly doesn't use a for loop to sum a column. The code for this will be similar to the code for the sumRow method except you'll swap which array index is fixed and which one holds the loop index.

Next the magic method should per the comments return a boolean value, not void, and should have code in it that sums all rows and columns and sums both diagonals to see if all sums are the same. If so, then return true, and if not, false.

Finally for your printSquare (as you know has no code). You'll want to use nested for loops to print out the contents of the array. I suggest you give it a try, anything, and see what results come out. It also helps to write out the steps you want to do on paper before trying to commit it to Java code.

Best of luck!
• 04-22-2010, 01:16 AM
easybe
Thanks I went and on ahead and put in for loops for sumRow(), sumCol(), magic(). I kind of have something for the printSquare(), but still not quite sure. Here is half of the code of Square.java.

Code:

```//-------------------------------------- //create new square of given size //--------------------------------------         public Square(int size)         {                 square = new int[size][size];                 } //-------------------------------------- //return the sum of the values in the given row //--------------------------------------         public int sumRow(int row)         {                 int sum = 0;                 for(int col = 0; col < square.length; col++)                 {                         sum = sum + square[row][col];                 }                 return sum;         } //-------------------------------------- //return the sum of the values in the given column //--------------------------------------         public int sumCol(int col)         {                 int sum = 0;                 for (int row = 0; row < square.length; row++)                 {                         sum = sum + square[row][col];                 }                                                                 return sum;         } //-------------------------------------- //return the sum of the values in the main diagonal //--------------------------------------         public int sumMainDiag()         {                 int sum = 0;                 for (int j = 0; j < square.length; j++)                 {                         sum = sum + square[j][j];                 }                 return sum;         } //-------------------------------------- //return the sum of the values in the other ("reverse") diagonal //--------------------------------------         public int sumOtherDiag()         {                 int sum = 0;                 for (int j = 0; j < square.length; j++)                 {                         sum = sum + square[j][square.length-1-j];                 }                 return sum;         } //-------------------------------------- //return true if the square is magic (all rows, cols, and diags // have same sum), false otherwise //-------------------------------------- public boolean magic() {     boolean answer = true;     int sum = sumMainDiag();     if (sumOtherDiag()!= sum)     {             answer = false;     }     else     {         for (int row = 0; (row < square.length)&& answer; row ++)         {             if (sum != sumRow(row))             {                 answer = false;             }         }         for (int col = 0; (col < square.length)&& answer; col ++)         {             if (sum != sumCol(col))             {                 answer = false;             }         }                                 }     return answer; } //-------------------------------------- //read info into the square from the input stream associated with //the Scanner parameter //--------------------------------------         public void readSquare(Scanner scan)         {                 for (int row = 0; row < square.length; row++)                 for (int col = 0; col < square.length; col++)                 square[row][col] = scan.nextInt();         } //-------------------------------------- //print the contents of the square, neatly formatted //-------------------------------------- public String printSquare()         {                 for (int row = 0; row < square.length; row++)                 for (int col = 0; col < square.length; col++)                 {                         System.out.print(square[row][col] + " ");                         System.out.println();                 }         }                                 }```

*NOTE*

Also for the SquareTest.java, I had to read in the inputs and print the results, but I still just need suggestions if I formatted it correctly.

Thanks
• 04-22-2010, 01:22 AM
Fubarable
Ha! You've been sandbagging us! This current code looks much better! :)

One suggestion I have to make: whenever creating a loop or if block, or pretty much any block, always, always surround your code blocks with curly braces, even if they aren't necessary as they'll save your tail at some point. As for your printSquare method, have you run it yet? I imagine it will print out one long line of data meaning you'll want to add a System.out.println() statement in there somewhere. Here's one place having the curly braces already in place will help prevent disaster.

Much luck!
• 04-22-2010, 01:40 AM
easybe
LoL I didnt think I was sandbagging anyone :D. I changed the code around at the top with the curly brackets...I try to use those whenever I can, when I insert a loop. I'm using Eclipse, and I'm getting the error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type String

at Square.printSquare(Square.java:136)
at SquareTest.main(SquareTest.java:39)

I know it needs to return the type as a String...so now my heads hurts....:confused:
• 04-22-2010, 02:03 AM
Fubarable
Code:

```public String printSquare()   {       for (int row = 0; row < square.length; row++)       {  // don't forget this curly brace too!         for (int col = 0; col < square.length; col++)         {             System.out.print(square[row][col] + " ");             System.out.println();  // are you sure you want this here?         }       }   }```

but since the method signature (the top line of the method) states that it will return a String, an error will be shown if it doesn't in fact return a String. But before you change it to return a String, let's look at the test class. In it, printSquare is used like so:
Code:

```        //print the square         s.printSquare();```

So the method appears to print the square to the console but has no need to return a String. Thus your method signature is likely wrong. Instead of this:
Code:

`public String printSquare()`

perhaps you want to state the the method will return nothing or void:
Code:

`public void printSquare()`
• 04-22-2010, 07:21 PM
easybe
Quote:

Well when I went to run the program it always gives me the number 0 throughout (I have no null as my return statement in printSquare(), I have to upload the magicData file (which is in SquareTest.java). ...maybe that is the reason why I keep getting the 0 throughout the program?

Actually the code is suppose to be this:

Code:

``` public void printSquare()   {     }```

This is what happens when you don't read the skeleton code...:D
• 04-22-2010, 07:50 PM
JosAH
Quote:

Originally Posted by easybe