使用Java打印數(shù)字組成的魔方陣及字符組成的鉆石圖形
打印魔方陣
輸入一個自然數(shù)N(2≤N≤9),要求輸出如下的魔方陣,即邊長為N*N,元素取值為1至N*N,1在左上角,呈順時針方向依次放置各元素。 N=3時:
1 2 3 8 9 4 7 6 5
【輸入形式】 從標準輸入讀取一個整數(shù)N。
【輸出形式】 向標準輸出打印結(jié)果。輸出符合要求的方陣,每個數(shù)字占5個字符寬度,向右對齊,在每一行末均輸出一個回車符。
【輸入樣例】 4
【輸出樣例】
1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
實現(xiàn):
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--;
}
}
}
}
相關文章
idea2019版與maven3.6.2版本不兼容的解決方法
這篇文章主要介紹了idea2019版與maven3.6.2版本不兼容的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-10-10
SpringCloud @FeignClient注入Spring容器原理分析
本文詳細分析了Spring Boot中@FeignClient注解的掃描和注入過程,重點探討了@EnableFeignClients注解的工作原理,通過源碼分析,揭示了@EnableFeignClients如何通過@Import注解和FeignClientsRegistrar類實現(xiàn)bean定義的加載2024-12-12
永中文檔在線轉(zhuǎn)換服務Swagger調(diào)用說明
這篇文章主要為大家介紹了永中文檔在線轉(zhuǎn)換服務Swagger調(diào)用說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06
Java?GenericObjectPool?對象池化技術(shù)之SpringBoot?sftp?連接池工具類詳解
這篇文章主要介紹了Java?GenericObjectPool?對象池化技術(shù)之SpringBoot?sftp?連接池工具類詳解,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04
實例解析使用Java實現(xiàn)基本的音頻播放器的編寫要點
這篇文章主要介紹了使用Java實現(xiàn)基本的音頻播放器的代碼要點實例分享,包括音頻文件的循環(huán)播放等功能實現(xiàn)的關鍵點,需要的朋友可以參考下2016-01-01

