- Start your Eclipse IDE
- Type the following code in a class named MagicSquare:
import java.util.Scanner;
public class MagicSquare {
public static void main(String[] args) {
System.out.println("Welcome to MagicBox");
System.out.println("---------------------------------------------------------------------------");
System.out.println("Enter any odd number for which you want to create a magic box.(Greater than 1");
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
if (n%2==0) {System.out.println("You didn't enter an odd number");System.exit(0);}
System.out.println("---------------------------------------------------------------------------");
int ct=1;
int a[][]=new int[n][n];
int x=(n+1)/2;
int y=(n-1)/2;
for (int i=0;i<n;i++) {
for (int j=0;j<n;j++) {
a[x][y]=ct;
ct++;x++;y--;
if (x==n) {x=0;}
if (y==-1) {y=n-1;}
}
x=(x+1)%n;y++;if (y==n) {y=0;}
}
int num=(int) Math.floor(Math.log10((double)(Math.pow(n, 2)))+1);
for (int i=0;i<n;i++) {
for (int j=0;j<n;j++) {
if (Math.floor(Math.log10((double)a[j][i])+1)>num) {num=a[j][i];}
}
}
String space="";
double spc=0;
for (int i=0;i<n;i++) {
for (int j=0;j<n;j++) {
spc=num-Math.floor(Math.log10((double)a[j][i])+1);
for (int abc=0;abc<spc;abc++) {
space=space+" ";
}
System.out.print(" |"+" "+a[j][i]+space);
space="";
}
System.out.println(" |");
}
}
}
- Execute the code
No comments:
Post a Comment