简体   繁体   English

使用循环在Java中绘制等腰三角形

[英]Drawing Isosceles Triangle in Java Using Loops

This is the problem: 这就是问题:
Create an IsoTri application that prompts the user for the size of an isosceles triangle and then displays the triangle with that many lines. 创建一个IsoTri应用程序,提示用户输入等腰三角形的大小,然后显示包含这么多行的三角形。

Example: 4 示例:4

*
**
***
****
***
**
*

The IsoTri application code should include the printChar(int n, char ch) method. IsoTri应用程序代码应包括printChar(int n, char ch)方法。 This method will print ch to the screen n times. 此方法将ch打印到屏幕n次。

This is what I have so far: 这是我到目前为止的内容:

public static void main(String[] args) {
        int n = getInt("Give a number: ");
        char c = '*';
        printChar(n, c);


    }

    public static int getInt(String prompt) {
        int input;

        System.out.print(prompt);
        input = console.nextInt();

        return input;
    }

    public static void printChar(int n, char c) {
        for (int i = n; i > 0; i--) {
            System.out.println(c);
        }

    }

I'm not sure how to get it to print the triangle. 我不确定如何打印三角形。 Any help is appreciated. 任何帮助表示赞赏。

You need two nested for loops: 您需要两个嵌套的for循环:

public static void printChar(int n, char c) {
    // print the upper triangle
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < i + 1; ++j) {
            System.out.print(c);
        }
        System.out.println();
    }

    // print the lower triangle
    for (int i = n - 1; i > 0; --i) {
        for (int j = 0; j < i; ++j) {
            System.out.print(c);
        }
        System.out.println();
    }
}

First of all your printChar is wrong. 首先,您的printChar是错误的。 It will print every * in a new line. 它将在新行中打印每个* You need to print the * character n times and then a new line. 您需要先打印*字符n次,然后换一行。 Eg 例如

public static void printChar(int n, char c) {
    for (int i = n; i > 0; i--) {
        System.out.print(c);
    }
    System.out.println();
}

After that given you have to use printChar I would recommend 2 for loop one one incrementing one deincrementing 在那之后给定你必须使用printChar我会建议2循环一一递增一递减

public static void main(String[] args) {
    int n = getInt("Give a number: ");
    char c = '*';

    // first 3 lines
    for (int i = 1; i < n; ++i)
        printChar(i, c);

    // other 4 lines
    for (int i = n; i > 0; --i)
        printChar(i, c);
}

A little recursive solution: 一点递归解决方案:

private static String printCharRec(String currStr, int curr, int until, char c) {
    String newStr = "";
    for (int i = 1; i < curr; i++)
        newStr += c;
    newStr += '\n';
    currStr += newStr;

    if (curr < until) {
        currStr = printCharRec(currStr, curr+1, until, c);
        currStr += newStr;
    }

    return currStr;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM