所以我需要制作一个程序,让用户输入高度并使用嵌套循环输出以下形状:
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
我想让它起作用的想法是使用一个字符作为黑色空间,并在给定高度时将其对应于正确形状所需的空间数。但是,我无法调用它。我如何制作 char,在同一行上运行一定次数。我希望它与第二个循环中的“x”值相对应。
import java.util.Scanner;
public class TrueArt
{
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
int height;
char star = '*';
// Gets preferred height
System.out.println("Enter the height you want the masterpiece to be: ");
height = sc.nextInt();
for (int i=0; height > i; i--)
{
for (int x = 0; x < height; i++)
{
1 + x * 2
}
}
}
}
提前感谢您的任何建议!
最佳答案
要获得您想要的输出,您可以使用金字塔算法。
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int height = s.nextInt();
char star = '*';
for(int i = 0;i < height; i++) {
for(int j = 0; j < height - i; j++) {
System.out.print(" ");
}
for(int k = 0; k <= i; k++) {
System.out.print(star + " ");
}
System.out.println();
}
}
您必须稍微更改一下以获得您想要的特定形状/样式金字塔,但为了学习目的,这是需要解决的问题。
关于java - 将 char 添加与数字一样多的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32314237/