试题描述:下图是一个3行3列包括9个字符的图形。
# #
#
# #
第一层次的的打印效果和原图一样:
# #
#
# #
第二层次的打印效果是一种9行9列的嵌套显示:
# # # #
# #
# # # #
# #
#
# #
# # # #
# #
# # # #
程序代码如下,请补充完整。
纯属个人见解,如果有什么问题、疑惑或者更好的算法,欢迎在评论区留言
1 package cn.tudou;
2
3 public class Demo9 {
4 public static void main(String[] args) {
5 String template[] = { "* *", " * ", "* *" };
6 int level = 2;
7 copy(template, template, level);
8 }
9
10 private static void copy(String[] template1, String[] template2, int level) {
11 --level;
12 if (level > 0) {
13 int n1 = template1.length;
14 int n2 = template2.length;
15 String[] tmpTemplate = new String[n2 * n1]; // 第1行所缺代码
16 int k = 0;
17 String spaceS = spaceStr(n2);
18 for (int i = 0; i < n1; ++i) {
19 for (int j = 0; j < n1; ++j) {
20 k = i * n2;
21 if (template1[i].charAt(j) == ' ') {
22 for (int x = 0; x < n2; ++x) {
23 if (tmpTemplate[k] != null)
24 tmpTemplate[k] += (spaceS);
25 else
26 tmpTemplate[k] = new String(spaceS);
27 k++;
28 }
29 } else {
30 for (int x = 0; x < n2; ++x) {
31 if (tmpTemplate[k] != null)
32 tmpTemplate[k] += template1[x]; // 第2行所缺代码
33 else
34 tmpTemplate[k] = new String(template1[x]); // 第3行所缺代码
35 k++;
36 }
37 }
38 }
39 }
40 copy(template1, tmpTemplate, level); // 第4行所缺代码
41 } else
42 print(template2); // 第5行所缺代码
43 }
44
45 private static String spaceStr(int n) {
46 StringBuilder sb = new StringBuilder();
47 for (int i = 0; i < n; ++i) {
48 sb.append(" ");
49 }
50 return sb.toString();
51 }
52
53 private static void print(String[] template) {
54 int n = template.length;
55 for (int i = 0; i < n; ++i) {
56 System.out.print(template[i]);
57 System.out.println();
58 }
59 }
60 }
GitHub : https://github.com/fxiaoyu97
微信公众号 : 三更编程菌