使用Java打印數(shù)字組成的魔方陣及字符組成的鉆石圖形
打印魔方陣
輸入一個自然數(shù)N(2≤N≤9),要求輸出如下的魔方陣,即邊長為N*N,元素取值為1至N*N,1在左上角,呈順時針方向依次放置各元素。 N=3時:
1 2 3 8 9 4 7 6 5
【輸入形式】 從標(biāo)準(zhǔn)輸入讀取一個整數(shù)N。
【輸出形式】 向標(biāo)準(zhǔ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--; } } } }
相關(guān)文章
java實現(xiàn)ArrayList根據(jù)存儲對象排序功能示例
這篇文章主要介紹了java實現(xiàn)ArrayList根據(jù)存儲對象排序功能,結(jié)合實例形式分析了java針對ArrayList的相關(guān)運算、排序操作技巧,需要的朋友可以參考下2018-01-01Java畢業(yè)設(shè)計實戰(zhàn)之養(yǎng)老院管理系統(tǒng)的實現(xiàn)
讀萬卷書不如行萬里路,只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+JSP+Easyui+maven+mysql實現(xiàn)一個養(yǎng)老院管理系統(tǒng),大家可以在過程中查缺補(bǔ)漏,提升水平2022-03-03SpringBoot的@EnableAsync和@Async注解分析
這篇文章主要介紹了SpringBoot的@EnableAsync和@Async注解分析,Spring Boot是一個快速開發(fā)框架,可以幫助開發(fā)人員快速構(gòu)建基于Spring的應(yīng)用程序,需要的朋友可以參考下2023-07-07如何利用postman完成JSON串的發(fā)送功能(springboot)
這篇文章主要介紹了如何利用postman完成JSON串的發(fā)送功能(springboot),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07