gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:29:36 24 4
gpt4 key购买 nike

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

最佳答案

要居中一条线,使用这个:

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
}
}

关于java - 使用嵌套 for 循环创建带星号的三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19273231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com