Results 1 to 8 of 8
  1. #1
    ndsmith20 is offline Member
    Join Date
    Oct 2012
    Posts
    55
    Rep Power
    0

    Default Need help with MagicSquare problem

    Write a program that reads in n^2 values from the keyboard and tests whether they form a magic square when arranged as a square matrix. This is what I have so far:

    Java Code:
    import java.util.*;
    
       public class Square
       {
       	//attributes
          ArrayList<Integer> numbers; 	
          int[][] square;
          private int row;
          private int col; 
       	
       	//constructor
          public Square()
          {
             numbers = new ArrayList<Integer>();
             square = new int[row][col];
          }
       	
       	//add numbers
          public void add(int i)
          {
             numbers.add(i);
          }
       	
    		//make a square
    		public void makeSquare()
          {
    			int s = 0;
             for (int row=0; row < numbers.size(); row++)
             {	
    				
                for (int col=0; col < numbers.size(); col++)
                {
                   square[row][col] = (int) numbers.get(s);
    					s++; 
                }
             }
          
          }
       	
    		//check to see if square was created
          public boolean isSquare()
          {
             if(square[row].length == square[col].length)
                return true;
             else
                return false;
          }
    		
    		//check for number uniqueness
    		public boolean isUnique()
    		{
    			int s = 0;
    			if(numbers.get(s) == numbers.get(s+1))
    				return false;
    			else
    				return true;
    		}
    		
       	//test if a magic square
          public boolean isMagic()
          {
          // get value first row
             int keyVal = 0;
             for(int col = 0; col < numbers.size(); ++col) 
             {
                keyVal += square[0][col];
             }
          
          // validate all rows match
             for(int row = 1; row < numbers.size(); ++row) 
             {
                int total = 0;
                for(int col = 0; col < numbers.size(); ++col) 
                {
                   total += square[row][col];
                }
             
             // total of the rows differ
                if(total != keyVal)
                   return false;
             }
          
          // validate the columns
             for(int col = 0; col < numbers.size(); ++col) 
             {
                int total = 0;
                for(int row = 0; row < numbers.size(); ++row) 
                {
                   total += square[row][col];
                }
             
             // total of the rows differ
                if(total != keyVal)
                   return false;
             }
             int total = 0;
          
          // check the first diagonal
             for(int row = 0; row < numbers.size(); ++row) 
             {
                total += square[row][row];
             }
             if(total != keyVal)
                return false;
          // check the second diagonal
             total = 0;
             for(int row = 0; row < numbers.size(); ++row) 
             {
                int col = numbers.size() - row - 1;
                total += square[row][col];
             }
             if(total != keyVal)
                return false;
          
          // OK everything matches
             return true;
          }
       
       	
       
       }
    
    
     import java.util.*;
    
       public class TestMagicSquare
       {
          public static void main(String[] args)
          {
          //attributes
             int row;
             int col;
             ArrayList<Integer> numbers;
             int[][] square;
             String i;
          
    		
    		//create arrayList
    			Square magic = new Square();
         
    	   //way to enter numbers into array
             Scanner test = new Scanner(System.in);
             System.out.print("Enter an integer(x to exit): ");
             i = test.next();
          
            	while(i.substring(0,1) != ("x"))
             {
    				//verifies that entry is integer
    				int s = Integer.parseInt(i);
                if(s/1 != s)
                {
                   System.out.println("*****Invalid data entry*****");
                   System.out.print("Enter an integer(x to exit): ");
                   i = test.next();
                }
                else
                {	
    					magic.add(s);
                   System.out.print("Enter an integer(x to exit): ");
                   i = test.next();
                }
             }
          	
    			//Attempts to create square and tests
    			magic.makeSquare();
    			if(magic.isSquare() == true)
    				{
    					System.out.println("\nStep 1: Numbers make a sqaure ***");
    				}
    			else
    				{
    					System.out.println("\nStep 1: Numbers do not make a square: Program Stopped");
    					System.out.println("\nPress any key to continue...");
    				}	
          	
          }
       }
    this is the error i get:

    Enter an integer(x to exit): x
    Exception in thread "main" java.lang.NumberFormatException: For input string: "x"
    at java.lang.NumberFormatException.forInputString(Num berFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)
    at java.lang.Integer.parseInt(Integer.java:527)
    at TestMagicSquare.main(TestMagicSquare.java:26)

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Need help with MagicSquare problem

    Don't use == or != to test for String equality. These operators test if two variables refer to the very same *object* which is not what you desire to test. You want to know if the Strings hold the same chars in the same order. Instead use the equals or equalsIgnoreCase method.

    so instead of (i.substring(0,1) != ("x"))

    do either:

    Java Code:
    (!i.substring(0,1).equalsIgnoreCase("x"))
    Note you *could* do:
    Java Code:
    (i.charAt(0) != 'x')
    because == and != will work well for primitive types but not for reference types like String.
    Last edited by Fubarable; 12-05-2012 at 11:28 PM.

  3. #3
    ndsmith20 is offline Member
    Join Date
    Oct 2012
    Posts
    55
    Rep Power
    0

    Default Re: Need help with MagicSquare problem

    Thank you, I made the change and I am now receiving this error:

    Enter an integer(x to exit): 4
    Enter an integer(x to exit): 3
    Enter an integer(x to exit): 2
    Enter an integer(x to exit): 6
    Enter an integer(x to exit): 5
    Enter an integer(x to exit): x
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at Square.makeSquare(Square.java:33)
    at TestMagicSquare.main(TestMagicSquare.java:42)

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Need help with MagicSquare problem

    You're trying to access an empty array. Please show the changed code and indicate the lines throwing the exception.

  5. #5
    ndsmith20 is offline Member
    Join Date
    Oct 2012
    Posts
    55
    Rep Power
    0

    Default Re: Need help with MagicSquare problem

    Java Code:
      import java.util.*;
    
       public class Square
       {
       	//attributes
          ArrayList<Integer> numbers; 	
          int[][] square;
          private int row;
          private int col; 
       	
       	//constructor
          public Square()
          {
             numbers = new ArrayList<Integer>();
             square = new int[row][col];
          }
       	
       	//add numbers
          public void add(int i)
          {
             numbers.add(i);
          }
       	
    		//make a square
    		public void makeSquare()
          {
    			int s = 0;
             for (int row=0; row < numbers.size(); row++)
             {	
    				
                for (int col=0; col < numbers.size(); col++)
                {
                   square[row][col] = (int) numbers.get(s); //THIS IS LINE WHERE ERROR IS OCCURING
    					s++; 
                }
             }
          
          }
       	
    		//check to see if square was created
          public boolean isSquare()
          {
             if(square[row].length == square[col].length)
                return true;
             else
                return false;
          }
    		
    		//check for number uniqueness
    		public boolean isUnique()
    		{
    			int s = 0;
    			if(numbers.get(s) == numbers.get(s+1))
    				return false;
    			else
    				return true;
    		}
    		
       	//test if a magic square
          public boolean isMagic()
          {
          // get value first row
             int keyVal = 0;
             for(int col = 0; col < numbers.size(); ++col) 
             {
                keyVal += square[0][col];
             }
          
          // validate all rows match
             for(int row = 1; row < numbers.size(); ++row) 
             {
                int total = 0;
                for(int col = 0; col < numbers.size(); ++col) 
                {
                   total += square[row][col];
                }
             
             // total of the rows differ
                if(total != keyVal)
                   return false;
             }
          
          // validate the columns
             for(int col = 0; col < numbers.size(); ++col) 
             {
                int total = 0;
                for(int row = 0; row < numbers.size(); ++row) 
                {
                   total += square[row][col];
                }
             
             // total of the rows differ
                if(total != keyVal)
                   return false;
             }
             int total = 0;
          
          // check the first diagonal
             for(int row = 0; row < numbers.size(); ++row) 
             {
                total += square[row][row];
             }
             if(total != keyVal)
                return false;
          // check the second diagonal
             total = 0;
             for(int row = 0; row < numbers.size(); ++row) 
             {
                int col = numbers.size() - row - 1;
                total += square[row][col];
             }
             if(total != keyVal)
                return false;
          
          // OK everything matches
             return true;
          }
       
       	
       
       }
    
     import java.util.*;
    
       public class TestMagicSquare
       {
          public static void main(String[] args)
          {
          //attributes
             int row;
             int col;
             ArrayList<Integer> numbers;
             int[][] square;
             String i;
          
    		
    		//create arrayList
    			Square magic = new Square();
         
    	   //way to enter numbers into array
             Scanner test = new Scanner(System.in);
             System.out.print("Enter an integer(x to exit): ");
             i = test.next();
          
            	while(i.charAt(0) != 'x')//THE CHANGED CODE
             {
    				//verifies that entry is integer
    				int s = Integer.parseInt(i);
                if(s/1 != s)
                {
                   System.out.println("*****Invalid data entry*****");
                   System.out.print("Enter an integer(x to exit): ");
                   i = test.next();
                }
                else
                {	
    					magic.add(s);
                   System.out.print("Enter an integer(x to exit): ");
                   i = test.next();
                }
             }
          	
    			//Attempts to create square and tests
    			magic.makeSquare();//THIS IS CAUSING THE EXCEPTION
    			if(magic.isSquare() == true)
    				{
    					System.out.println("\nStep 1: Numbers make a sqaure ***");
    				}
    			else
    				{
    					System.out.println("\nStep 1: Numbers do not make a square: Program Stopped");
    					System.out.println("\nPress any key to continue...");
    				}	
          	
          }
       }
    Last edited by ndsmith20; 12-06-2012 at 12:03 AM.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Need help with MagicSquare problem

    Please edit your above post to add the closing [/code] tag.

    Since it's the makeSquare(...) method that is buggy, why not debug it by printing out at the start of the method the length of the array, square. Use a println, and next you'll want to trace back into your program to see why length is giving the bad result that you are seeing. It will become obvious to you when you see it.

  7. #7
    ndsmith20 is offline Member
    Join Date
    Oct 2012
    Posts
    55
    Rep Power
    0

    Default Re: Need help with MagicSquare problem

    ok I will try that fubarable

  8. #8
    RSchmidt624 is offline Member
    Join Date
    Mar 2013
    Posts
    1
    Rep Power
    0

    Default Re: Need help with MagicSquare problem

    Quote Originally Posted by ndsmith20 View Post
    ok I will try that fubarable


    What was the result, I looked over the code too and can't seem to get it to work. I did the println statement in the makeSquare method and it returns 0. I get that the array size is 0 and can't enter values into it until it has a set size but I don't know how to fix it.

Similar Threads

  1. Replies: 0
    Last Post: 11-07-2012, 12:44 PM
  2. MagicSquare.java Printing
    By dgoff267 in forum New To Java
    Replies: 3
    Last Post: 03-24-2012, 12:40 AM
  3. [Help] Arrays and MagicSquare
    By sexy_programmer in forum JCreator
    Replies: 3
    Last Post: 11-16-2011, 02:36 PM
  4. Small problem with problem with Java, C++ parse program.
    By dragstang86 in forum New To Java
    Replies: 4
    Last Post: 10-30-2011, 03:43 AM
  5. Replies: 9
    Last Post: 09-21-2010, 04:15 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •