使用嵌套for循环创建带星号的三角形

时间:2013-10-09 13:18:36

标签: java geometry

使用嵌套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();
    }
  }
}
}

5 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分: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
}

答案 2 :(得分:0)

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

答案 3 :(得分: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写入输出流),以便星号*打印在同一行上。< / p>

答案 4 :(得分:0)

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

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

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

相关问题