java 打印一个三角形

java print a triangle

我正在尝试制作一个程序来接受用户输入,例如三角形应该有多长及其方向。我遇到的问题是,在我 运行 它之后,它不断地向程序添加更多数字。

例如

State the length of the two sides (finish with -1):  5
Should the triangle face down (0) or  up(1): 1
*
**
***
****
*****

2
Should the triangle face down (0) or  up(1): 1
*
**
***
****
*****
******
*******

我的代码:

import java.util.Scanner; 

public class Triangel {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        // Initierings variabler för triangelsida.
        double length = 0;
        double sideLength = 0;

        // This part will ask for user input
        System.out
                .print("State the length of the two sides (finish with -1): ");

        while (sideLength != -1) {
            // Input.
            sideLength = in.nextDouble();
            if (sideLength != -1) {
                // Input will be saved in variable length.
                length += sideLength;

                // This part will ask the user to state whether the triangle is
                // up or down.
                System.out
                        .print("Should the triangle face down (0) or  up(1): ");
                String direction = in.next();

                // if the variables direction is equal to (1) this part will
                // run.
                if (direction.equals("1")) {
                    for (int i = 1; i <= ((int) (length)); i++) {
                        for (int j = 1; j <= i; j++) {
                            System.out.print("*");
                        }
                        System.out.println();
                    }

                }
                // if direction equals to (0) .
                else {
                    for (int i = 1; i <= ((int) (length)); i++) {
                        for (int j = ((int) (length)); j >= 1; j--) {
                            if (j >= i)
                                System.out.print("*");
                        }
                        System.out.println();
                    }
                }

            }

        }

    }

}

你有 length += sideLength。对于 while 循环的每个循环,这将继续将 sideLength 输入添加到 length 变量。您可能想要的只是 length = sideLength

要让它在每次迭代时再次打印出您的第一个提示,只需将您的 System.out.print("State the length of the two sides (finish with -1): "); 调用放在您的 while 循环中。 (它也需要在 sideLength = in.nextDouble(); 之前出现,以便在输入 输入之前 显示提示。)