Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: [HELP] I'm creating a code to check whether 2D array is Magic Square or not

  1. #1
    Junior Member
    Join Date
    Dec 2021
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default [HELP] I'm creating a code to check whether 2D array is Magic Square or not

    Hi everyone.

    I'm creating a method to check if a array is Magic Square or not.

    * Magic Square is a 2D array in which the sum of all rows, columns and diagonals are equal, for example:

    4|9|2
    3|5|7
    8|1|6

    The result of all sums are 15.

    Anyway... I started out by:

    1. Creating booleans to store the condition of rows, columns and diagonals, then another boolean to store if the square is magical or not (which depend of the other three booleans to be true).

    2. Then there are variables to store each sum of columns, rows an diagonals.

    3. The next thing is a for loop to iterate through the array (I think the problem is there), and then it checks if columns, rows and diagonals (separately) all have the same sum.

    4. In the last step, I check if the sum of all columns, rows and diagonals are the same. If they are, it must print a message saying it's Magic Square, otherwise it must print it's not.

    Here's the code:

    public class Ex2 {
     
    	public static void main(String []args) {
    		// Testing
    		int ex[][]  = {{4,9,2}, {3,5,7}, {8,1,6}};
    		isMagicSquare(ex);
    	}
     
    	public static void isMagicSquare(int arr[][]) {
     
    		boolean magic = true;
    		boolean rows = true;
    		boolean columns = true;
    		boolean diagonals = true;
     
    		int row1 = arr[0][0] +  arr[0][1] +  arr[0][2];
    		int row2 = arr[1][0] +  arr[1][1] +  arr[1][2];
    		int row3 = arr[2][0] +  arr[2][1] +  arr[2][2];
     
    		int col1 = arr[0][0] +  arr[1][0] +  arr[2][0];
    		int col2 = arr[0][1] +  arr[1][1] +  arr[2][1];
    		int col3 = arr[0][2] +  arr[1][2] +  arr[2][2];
     
    		int diag1 = arr[0][0] +  arr[1][1] +  arr[2][2];
    		int diag2 = arr[2][0] +  arr[1][1] +  arr[1][2];
     
    		for(int i = 0; i < arr.length; i++) {
    			for(int j = 0; j < arr[i].length; j++) {
     
    				if(row1 == row2 && row2 == row3) {
    					rows = true;
    				}
    				else if(col1 == col2 && col2 == col3){
    					columns = true;
    				}
    				else if(diag1 == diag2){
    					diagonals = true;
    				}
    			}
    		}
     
    		if(rows == true && columns == true && diagonals == true) {
    			magic = true;
    		}
     
    		if(magic == true) {
    			System.out.println("The array is a Magic Square.");
    		}else{
    			System.out.println("The array is not a Magic Square.");
     
    		}
    	}
    }

    The problem is that when I execute, it only prints that it's a Magic Square, even if it's not.
    Last edited by Guillaume_96; December 24th, 2021 at 05:35 PM.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: [HELP] I'm creating a code to check whether 2D array is Magic Square or not

    What happens when the code is executed?
    Why are the initial values of the boolean variables all set to true?

    It seems like the code does a lot of useless work. If all the summed values must be the same, then save the first value and compare each one in turn against that value. As soon as there is a mismatch, you have the answer.

    Look at a way to put the 8 sets of indexes into an array that can be used in a loop.

    Please edit your post and wrap your code with code tags:

    [code]
    **YOUR CODE GOES HERE**
    [/code]

    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Dec 2021
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: [HELP] I'm creating a code to check whether 2D array is Magic Square or not

    Quote Originally Posted by Norm View Post
    What happens when the code is executed?
    Why are the initial values of the boolean variables all set to true?

    It seems like the code does a lot of useless work. If all the summed values must be the same, then save the first value and compare each one in turn against that value. As soon as there is a mismatch, you have the answer.

    Look at a way to put the 8 sets of indexes into an array that can be used in a loop.

    Please edit your post and wrap your code with code tags:

    [code]
    **YOUR CODE GOES HERE**
    [/code]

    to get highlighting and preserve formatting.
    I just fixed the post!

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: [HELP] I'm creating a code to check whether 2D array is Magic Square or not

    Ok, did you read my comments?
    Answer this question: Why are the values of all the boolean variables initially set to true?

    it only prints that it's a Magic Square
    Where are any of those boolean variables ever set to false?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Dec 2021
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: [HELP] I'm creating a code to check whether 2D array is Magic Square or not

    Quote Originally Posted by Norm View Post
    Ok, did you read my comments?
    Answer this question: Why are the values of all the boolean variables initially set to true?


    Where are any of those boolean variables ever set to false?
    I had to initialize the boolean variables. That's why I set them to true. Now I set them all to false and it prints it's not a magic square...

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: [HELP] I'm creating a code to check whether 2D array is Magic Square or not

    Is it working correctly now?
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Dec 2021
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: [HELP] I'm creating a code to check whether 2D array is Magic Square or not

    No, because the array I tested the code on is a magic square. I initialized the booleans = false, and it prints it's not a magic square though. If I initialize them = true, then it prints it's magic square. So it's definitely not working...

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: [HELP] I'm creating a code to check whether 2D array is Magic Square or not

    Ok, which variable(s) have the wrong values? Look at the contents of all the variables to see which one(s) are wrong.
    One way to see a variable's value is to print it out.

    Note: If none of the boolean variables are ever set to false, then the results will always be true.

    Note: These statements can be reduced
    if(rows == true && columns == true && diagonals == true) {
    			magic = true;
    		}
    to this:
     magic = (rows == true && columns == true && diagonals == true);
    If you don't understand my answer, don't ignore it, ask a question.

  9. The Following User Says Thank You to Norm For This Useful Post:

    Guillaume_96 (December 25th, 2021)

  10. #9
    Junior Member
    Join Date
    Dec 2021
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: [HELP] I'm creating a code to check whether 2D array is Magic Square or not

    Quote Originally Posted by Norm View Post
    Ok, which variable(s) have the wrong values? Look at the contents of all the variables to see which one(s) are wrong.
    One way to see a variable's value is to print it out.

    Note: If none of the boolean variables are ever set to false, then the results will always be true.

    Note: These statements can be reduced
    if(rows == true && columns == true && diagonals == true) {
    			magic = true;
    		}
    to this:
     magic = (rows == true && columns == true && diagonals == true);
    Nevermind man... I just figured out the problem. I changed the initial values of the booleans:

                    boolean magic = false;
    		boolean rows = false;
    		boolean columns = true;
    		boolean diagonals = true;

    And somehow the algorithm is working now, I just can't explain why! Lol

    Thank you so much for helping!

  11. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: [HELP] I'm creating a code to check whether 2D array is Magic Square or not

    That is not the fix that is needed. Try the code with other input values with invalid content in the columns or diagonals to see what happens.

    If the values of the booleans are never set false, they will stay true no matter what the contents of the array.
    Where does the code set columns or diagonals false?
    If you don't understand my answer, don't ignore it, ask a question.

  12. #11
    Member
    Join Date
    Jan 2024
    Posts
    75
    Thanks
    0
    Thanked 4 Times in 4 Posts

    Default Re: [HELP] I'm creating a code to check whether 2D array is Magic Square or not

    The issue lies in the logic of your code where you're checking the conditions for rows, columns, and diagonals inside nested loops. Let's fix it. Here's a corrected version of your `isMagicSquare` method:

    ```java
    public static void isMagicSquare(int arr[][]) {

    boolean magic = true;
    boolean rows = true;
    boolean columns = true;
    boolean diagonals = true;

    int row1 = arr[0][0] + arr[0][1] + arr[0][2];
    int row2 = arr[1][0] + arr[1][1] + arr[1][2];
    int row3 = arr[2][0] + arr[2][1] + arr[2][2];

    int col1 = arr[0][0] + arr[1][0] + arr[2][0];
    int col2 = arr[0][1] + arr[1][1] + arr[2][1];
    int col3 = arr[0][2] + arr[1][2] + arr[2][2];

    int diag1 = arr[0][0] + arr[1][1] + arr[2][2];
    int diag2 = arr[2][0] + arr[1][1] + arr[0][2];

    // Check rows
    if(row1 != row2 || row2 != row3){
    rows = false;
    }

    // Check columns
    if(col1 != col2 || col2 != col3){
    columns = false;
    }

    // Check diagonals
    if(diag1 != diag2){
    diagonals = false;
    }

    if(!rows || !columns || !diagonals) {
    magic = false;
    }

    if(magic) {
    System.out.println("The array is a Magic Square.");
    } else {
    System.out.println("The array is not a Magic Square.");
    }
    }
    ```

    Here's what changed:
    - Moved the checks for rows, columns, and diagonals outside of the nested loops.
    - Corrected the calculation of `diag2` to use `[2][0]` instead of `[1][2]`.
    - Changed the conditions for rows, columns, and diagonals to check for inequality (`!=`) rather than equality (`==`).
    - Removed unnecessary nested loops since you're already calculating sums outside the loops.

    If you're still encountering difficulties and need help with Java assignment, don't hesitate to reach out for help. There are various resources available online where you can find guidance and support with your programming tasks. Additionally, seeking assistance from programming communities or educational platforms can offer valuable insights and solutions to your coding challenges. You may also explore reliable online platforms like ProgrammingHomeworkHelp.com for further assistance.

Similar Threads

  1. [SOLVED] Magic Square.
    By pau_ emmanuel in forum What's Wrong With My Code?
    Replies: 2
    Last Post: September 12th, 2014, 11:11 AM
  2. Magic Square
    By aspic in forum What's Wrong With My Code?
    Replies: 2
    Last Post: December 31st, 2013, 06:58 AM
  3. JAVA MAGIC SQUARE
    By hiimjoey11 in forum What's Wrong With My Code?
    Replies: 11
    Last Post: November 28th, 2012, 12:42 AM
  4. Magic Square Checker
    By Hypnos in forum Object Oriented Programming
    Replies: 1
    Last Post: April 3rd, 2011, 06:37 PM
  5. Magic square class (modular math problem)
    By mjpam in forum What's Wrong With My Code?
    Replies: 1
    Last Post: June 30th, 2010, 10:56 AM

Tags for this Thread