2

使用嵌套的 for 循环语句来绘制 " " 的三角形。最后一行的“ ”个数由用户输入(有效范围:5 到 21)。输出应如下所示: 示例输出:

多少颗星/最后一排 (5-21)?25 超出范围。重新进入:7

* 
** 
*** 
**** 
***** 
****** 
*******

到目前为止,这就是我所拥有的代码。我不知道如何让它看起来像一个三角形。任何帮助都会很棒。

import java.util.Scanner;

public class Lab7_2{
  public static void main(String[] args){
    //declarations
    Scanner input= new Scanner(System.in);
    int how_many;//num of triangles
    int m; //constant
    int c;//constant
    int rows;//row

    //prompt for input
    System.out.println("Drawing triangles program.");
    System.out.println("==============================");
    System.out.println("How many triangles?");
    how_many=input.nextInt();
    System.out.println("How many stars/last row (5-21)?");
    rows=input.nextInt();
    while(rows<=5||rows>=21){
      System.out.println("Out of range. Reenter: ");
      rows=input.nextInt();
    }
    for(m=1;m<=rows;m++){
      for(c=1;c<=m;c++){
        System.out.println("*");
        System.out.println();
    }
  }
}
}
4

5 回答 5

2

要使一条线居中,请使用以下命令:

private static String center(String line, int length) {
    StringBuilder newLine = new StringBuilder();
    for (int i = 0; i < (line.length() - length)/2; i++)
        newLine.append(" ");
    }
    newLine.append(line);
    return newLine.toString();
}

还,

System.out.println();

在每个字符串之后打印一个换行符,这不是您想要的。


固定代码:

private void printTriangle(int base) {
    StringBuilder currentStars = new StringBuilder();
    for (int currLine = 1; currLine < base; currLine++) {
        currentStars.append("*"); // Don't create a new String, just append a "*" to the old line.
        //if (currLine % 2 == 1)
        //    System.out.println(center(currentStars.toString(), base)); // For centered triangle
        System.out.println(currentStars.toString()); // For non-centered triangle
    }
}
于 2013-10-09T13:25:12.360 回答
1

您正在使用 println 语句来打印您的星星,因此无论如何每个星星都将在自己的行上

System.out.println("*");

你想要一个打印语句

System.out.print("*");

此外,在星形打印循环内,您还有一个额外System.out.println();的空行,应该在内部 for 循环之外

for(m=1;m<=rows;m++){
  for(c=1;c<=m;c++){
    System.out.println("*"); <-- println always starts a new line, should be print
    System.out.println(); <--- shouldn't be within inner loop
  }
  <--- println() should be here to advance to the next line of stars
}
于 2013-10-09T13:23:51.903 回答
0

println()总是在输出后开始一个新行。尝试print代替,然后println()在内循环之后尝试。

于 2013-10-09T13:22:57.297 回答
0

只需将您的for循环修复为

for (m = 1; m <= rows; m++) {
    for (c = 1; c <= m; c++) {
        // first print the * on the same line
        System.out.print("*");
    }
    // then move to the next line
    System.out.println();
}

请注意,您需要使用System.out.print()(即不会将新行写入\n输出流)将星号*打印在同一行上。

于 2013-10-09T13:23:48.810 回答
0

我相信这是最有效和最简单的方法,在玩更大的金字塔时不必调用 print/println 方法数百次。

String out;
for (m = 0; m < rows; m++) {
    out = "";
    for (c = 0; c < m; c++) {
        out+="*";
        System.out.println(out);
    }
}

基本上你的字符串是“”,每次打印到下一行后都会添加一个“*”。

于 2013-10-09T14:35:30.467 回答