Print the Magic square
Enter a natural number N (2≤n≤9), which requires the output of the following magic square, that is, the length of the n*n, the element value is 1 to n*n,1 in the upper left corner, in turn, in the clockwise direction of the elements. When n=3:
Input form reads an integer n from the standard input.
The output form prints the results to the standard output. The output matches the required phalanx, each number is 5 characters wide, aligned to the right, and a carriage return is output at the end of each line.
"Input Sample" 4
"Output Sample"
Realize:
Package Cn.dfeng;
Import Java.util.Arrays;
Import Java.util.Scanner;
public class Maze {enum direction{up, down, right, left;
} public int[][] Buidmaze (int n) {int[][] maze = new Int[n][n];
For (int[] a:maze) {Arrays.fill (A, 0);
int col = 0;
int row = 0;
int counter = 1;
Direction d = direction.right;
while (true) {if (maze[row][col] = = 0) {Maze[row][col] = counter++; Switch (d) {case Right:if (col + 1< n && maze[row][col + 1] = = 0) {Co
L + +;
}else{d = direction.down;
Row + +;
} break;
Case Down:if (row + 1 < n && maze[row + 1][col] = = 0) {row + +;
}else{d = direction.left;
Col--;
} break; Case Left:if ( Col-1 >= 0 && maze[row][col-1] = = 0) {col-;
}else{d = direction.up;
Row--;
} break;
Default:if (row-1 >= 0 && maze[row-1][col] = = 0) {row-;
}else{d = direction.right;
Col + +;
} break;
}}else{break;
} return maze; public void Printmaze (int[][] maze) {for (int[] row:maze) {for (int i:row) {Sy
stem.out.printf ("%3d", I);
} System.out.println (); }/** * @param args */public static void main (string[] args) {Scanner sc = new Scanner (Sys
tem.in);
SYSTEM.OUT.PRINTLN ("Please input the size of the Maze:");
int size = Sc.nextint ();
Maze Maze = new Maze ();
int[][] m = maze.buidmaze (size); Maze.prinTmaze (m);
}
}
Print a diamond graphic
The effect of a diamond chart is probably this:
Now let's look at the code
Package Cn.dfeng;
/**
* This class can use * print size diamond graphics
* @author Dfeng * * */Public
class Drawer {
/**
* Print Diamond Graphics
* param n Diamond Size
*/public
void Printdiamond (int n) {
System.out.println ();
int i = 0;
Boolean flag = true;
while (I >= 0) {
if (I < n) {for
(int j = 0; J < N-i; J +)
{System.out.print ("");
} For
(int j = n-i; J <= N + i; j + + 2) {
System.out.print ("*");
}
System.out.println ();
}
if (i = = N) {
flag = false;
i--;
}
if (flag) {
i++}}
else {
i--;
}
}}}