1
import java.util.Scanner;
public class DrawTriangle
{
    public static void main(String[] args)
    {
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a height");
    while (!scan.hasNextInt()) // while non-integers are present
    {
        scan.next();
        System.out.println ("Bad input. Enter an integer.");
    }
    int input = scan.nextInt();
    for (int x = 1; x <= input; x++)
    {
        for (int y = 0; y < input; y++)
        {
            System.out.print(" ");

            for (int z = 1; z < y; z++)
            {
                System.out.print("x");
            }

            System.out.println();
        }
    }
}

}

我必须制作一个与用户指定的高度相关的 x 三角形。根本无法让它工作,任何帮助将不胜感激。谢谢!

抱歉应该澄清我需要它看起来像这样 -

   x
  xxx
 xxxxx
4

1 回答 1

2

您不需要最多 3 级的嵌套循环。刚2 levels需。One为 遍历columns,one为 遍历rows.

因此,将循环更改为: -

    for (int x = 1; x <= input; x++)
    {
        for (int y = 0; y < x; y++)
        {
            System.out.print("x ");
        }
        System.out.println();
    }

更新 : -

对于等边三角形,您需要x在开始行之前再添加一个循环以打印空格。这是代码: -

    for (int x = 1; x <= input; x++)
    {
        for (int y = 0; y < input - x; y++) {
            System.out.print(" ");
        }
        for (int y = 0; y < x; y++) {
            System.out.print("x ");
        }
        System.out.println();
    }
于 2012-11-22T20:30:54.133 回答