java打印一个三角形

发布于 2021-01-29 19:54:30

我正在尝试制作一个程序,该程序需要用户输入诸如三角形应该多长时间及其方向。我的问题是,在我运行该程序后,它会继续向程序中添加更多的数字。

例如

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();
                    }
                }

            }

        }

    }

}
关注者
0
被浏览
112
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看