双层棱形
程序员文章站
2022-03-27 19:53:07
...
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; public class 双层棱形 { public static void main(String[] args){ // 层数:8层 ,列宽:16 行宽:16 // * 号得总数为:层数*4-4 外层:8 则:内层 8-2 int n = 16; int[][] arr = new int[2*n+1][2*n+1]; int temp = 0; //代表 * 的个数 int x=1; int y=arr[x].length/2; // 起点为:中列 首行 arr[x][y] = 1; //1代表的是 * 号; //右下 while(arr[x+1][y+1]==0 && y+1<arr[x+1].length-1){ arr[++x][++y] = 1; ++temp; } //左下 while(arr[x+1][y-1]==0 && x+1<arr[x+1].length-1){ arr[++x][--y] = 1; ++temp; } // //左上 while(arr[x-1][y-1]==0 && y-1>0){ arr[--x][--y] = 1; ++temp; } //右上 while(arr[x-1][y+1]==0 && x-1>=0){ arr[--x][++y] = 1; ++temp; } // x=x+2; //---------------------------------------------内层---------------------------------------- //右下 arr[x+2][y] = 1; while(arr[x+1][y+1]==0 && y+1<arr[x+1].length-1-2){ arr[++x][++y] = 1; ++temp; } //左下 while(arr[x+1][y-1]==0 && x+1<arr[x+1].length-1-2){ arr[++x][--y] = 1; ++temp; } // //左上 while(arr[x-1][y-1]==0 && y-1>2){ arr[--x][--y] = 1; ++temp; } //右上 while(arr[x-1][y+1]==0 && x-1>=2){ arr[--x][++y] = 1; ++temp; } StringBuffer br = new StringBuffer(); for(int i=1;i<arr.length-1;i++){ String str = ""; for(int j=1;j<arr[i].length-1;j++){ str+=(arr[i][j]==1 ? "*":" "); System.out.print(arr[i][j]==1 ? "*" : " "); } bufferedWriter(str); str = ""; System.out.println(); } } //写入文件 public static void bufferedWriter(String str){ File f = new File("e:\\show.txt"); // String str = new String(s); try { if(!f.exists()){ f.createNewFile(); } BufferedWriter br = new BufferedWriter(new FileWriter(f,true)); br.write(str); br.write("\r\n"); br.close(); } catch (Exception e) { e.printStackTrace(); } } }