我正在尝试打印一个三角形的字符。我想要这样。
A
A B
A B C
A B C D
A B C D E
以下是我的代码。
public class Pro8Point3
{
public static void main(String[] args){
int space=29;
char ch;
for (int i=1; i<=5; i++) {
ch='A';
//Print spaces in decreasing order. A is at 29th position.
for (int j=1; j<=space; j++) {
System.out.println(" ");
}
//Print Triangle.
for (int k=1; k<=i; k++) {
System.out.print(ch+" ");
ch+=1;
}
space--;
// System.out.println();
}
System.out.println();
}
}
但它没有给我欲望输出。请指导我在哪里弄错了。
答案 0 :(得分:2)
System.out.println(" ");
应该是
System.out.print(" ");
你应该在for循环的底部取消注释这一行:
System.out.println();
最终代码,修复了格式并进行了上述更改:
public class Pro8Point3
{
public static void main(String[] args) {
int space=29;
char ch;
for (int i = 1; i <= 5; i++) {
ch = 'A';
//Print spaces in decreasing order. A is at 29th position.
for (int j = 1; j <= space; j++) {
System.out.print(" ");
}
//Print Triangle.
for (int k = 1; k <= i; k++) {
System.out.print(ch + " ");
ch+=1;
}
space--;
System.out.println();
}
}
}
输出:
A
A B
A B C
A B C D
A B C D E
答案 1 :(得分:2)
在@ smarx的正确答案之后,我想发布一个针对这种要求的通用方法。它可能看起来像这样
public class Pro8Point3 {
public static void main(String[] args) {
print(5, 20);
}
private static void print(int level, int position) {
for (int i = 0; i < level; i++) {
char c = 'A';
for(int j = 1; j < level + position - i; j++)
System.out.print(" ");
for(int j = 0; j <= i; j++)
System.out.print(Character.valueOf(c++) + " ");
System.out.println();
}
}
}