我要打印的图案是
1
1#
1#2
1#2#
1#2#3
1#2#3#
我写了以下代码:
public class Main {
public static void main (String args[]) {
int q = 2;
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= i; j++) {
if (j % 2 != 0) {
if (j > 2) {
System.out.print (q+ "");
} else {
System.out.print (j + "");
}
} else {
System.out.print("# ");
}
}
System.out.println();
}
}
}
,输出为:
1
1#
1# 2
1# 2#
1# 2# 2
1# 2# 2#
您可以简单地这样做:
public class Main {
public static void main(String args[]) {
StringBuilder s = new StringBuilder();
for (int i = 1; i <= 3; i++) {
s.append(i);
System.out.println(s);
s.append("#");
System.out.println(s);
}
}
}
只要继续添加字符串(生成器)并打印它。
或者,如果你不想用StringBuilder跟踪状态,你可以这样做:
public class Alternative {
public static void main(String args[]) {
int n = 3;
for (int i = 0; i < n * 2; i++) {
for (int j = 0; j <= i; j++) {
if (j % 2 == 0) {
System.out.print(j / 2 + 1);
} else {
System.out.print("#");
}
}
System.out.println();
}
}
}
由于您编写的逻辑,您正在获得错误的输出。您可以尝试下面的代码片段来实现相同的模式:
public class Main {
public static void main(String args[]) {
for (int i = 1; i <= 6; i++) {
int q = 1;
for (int j = 1; j <= i; j++) {
if (j % 2 == 0) {
System.out.print("#");
} else {
System.out.print(q);
q++;
}
}
System.out.println();
}
}
}