應用Java打印數字構成的魔方陣及字符構成的鑽石圖形。本站提示廣大學習愛好者:(應用Java打印數字構成的魔方陣及字符構成的鑽石圖形)文章只能為提供參考,不一定能成為您想要的結果。以下是應用Java打印數字構成的魔方陣及字符構成的鑽石圖形正文
打印魔方陣
輸出一個天然數N(2≤N≤9),請求輸入以下的魔方陣,即邊長為N*N,元素取值為1至N*N,1在左上角,呈順時針偏向順次放置各元素。 N=3時:
1 2 3 8 9 4 7 6 5
【輸出情勢】 從尺度輸出讀取一個整數N。
【輸入情勢】 向尺度輸入打印成果。輸入相符請求的方陣,每一個數字占5個字符寬度,向右對齊,在每行末均輸入一個回車符。
【輸出樣例】 4
【輸入樣例】
1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
完成:
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){
col ++;
}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 ){
System.out.printf("%3d", i);
}
System.out.println();
}
}
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.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 );
}
}
打印鑽石圖形
鑽石圖的後果年夜概就是如許的:
上面我們來看代碼
package cn.dfeng;
/**
* 該類可以或許用*打印年夜小的鑽石圖形
* @author dfeng
*
*/
public class Drawer {
/**
* 打印鑽石圖形
* @param n 鑽石年夜小
*/
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--;
}
}
}
}