0

hey guys i'm having problem to my code in MAGIC SQUARE

Output of my current code

0 1 8
7 5 3
2 9 4

it's a little bit confusing.. the 6th digit turn to 0


any help will be much appreciated :)
thanks in advance

import java.util.Scanner;

public class magicSquare {

	static Scanner sn = new Scanner(System.in);

    public static void main(String[] args) { 
    	System.out.print("Enter odd number: ");
        int N = sn.nextInt();
        if (N % 2 == 0) throw new RuntimeException("N must be odd");

        int[][] magic = new int[N][N];

        int row = 0;
        int col = N/2;
        magic[row][col] = 1;

        for (int i = 1; i <= N*N; i++) {
        	
        	magic[row][col] = i;
        	
        	--row;	// Move up
        	--col;	// Move left
        	
        	if(row <= 0 && col == 0){
        		row = N - 1;
        		col = 0;
        	}

        	if(row < 0){ row = N-1; }	// test if row need to wrap down
    
        	if(col < 0){ col = N-1; } 	// test if col need to wrap right
        		
        	if(magic[row][col] == 0) {
        		magic[row][col] = i;
        	}
        	else {	//check if the spot is taken.
        		int temp = col;
        		col = row-1;
        		row = col;
        		row = N-1;
        		
        		if (col < 0){
        			col = N - 1;
        		}
        	}
        }

        // print results
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (magic[i][j] < 10)  System.out.print(" ");  // for alignment
                if (magic[i][j] < 100) System.out.print(" ");  // for alignment
                System.out.print(magic[i][j] + " ");
            }
            System.out.println();
        }
    }
}
4
Contributors
7
Replies
8
Views
6 Years
Discussion Span
Last Post by bibiki
0

check lines 25-27 in your code and see what you might be doing wrong. that is where you're setting that zero that you're getting.

0

but if im going to change my code in line 25-27

the output will change...:( any suggestion sir?

0

then try to find the specific part of the code that gives the unwanted result
maybe print each array index one by one

0

but if im going to change my code in line 25-27

the output will change...:( any suggestion sir?

isn't that what you wanted?

0

problem solved guys..

i really appreciate your comments :D hope to see you again next time.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.