【发布时间】:2013-05-09 03:07:52
【问题描述】:
我正在尝试用循环在 Java 中制作一个看起来像这样的右侧三角形:
+
/|
/ |
/ |
/ |
+----+
程序需要将 args 作为 int 来确定三角形每个边的大小。现在这是我的代码:
public static void main(String[] args) {
int x = Integer.parseInt(args[0]);
for (int i = 0; i <= x; i++) {
for (int j = x; j >= i; j--) {
System.out.print(" ");
}
System.out.println("/");
}
System.out.print("+");
for (int j = 0; j < x; j++) {
System.out.print("-");
}
System.out.print("+");
}
到目前为止的结果是这样的
/
/
/
/
+---+
那么我应该如何处理呢?我尝试了一些 for 循环的组合,但到目前为止,它经常打印出乱七八糟的形状而不是实际的三角形。
【问题讨论】:
-
因为
/和|在同一行中,您只是缺少在同一语句中打印|,但两者之间有空格。计算出您需要多少个空格并将它们添加到您的/和|之间。