【问题标题】:Drawing Isosceles Triangle in Java Using Loops在 Java 中使用循环绘制等腰三角形
【发布时间】:2016-02-21 17:33:17
【问题描述】:

这就是问题所在:
创建一个 IsoTri 应用程序,提示用户输入等腰三角形的大小,然后显示具有那么多线条的三角形。

示例:4

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

IsoTri 应用程序代码应包含printChar(int n, char ch) 方法。此方法会将 ch 打印到屏幕 n 次。

这是我目前所拥有的:

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

    }

我不知道如何让它打印三角形。任何帮助表示赞赏。

【问题讨论】:

标签: java loops for-loop methods char


【解决方案1】:

你需要两个嵌套的 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();
    }
}

【讨论】:

    【解决方案2】:

    首先你的printChar 是错误的。它将在新行中打印每个*。您需要打印* 字符n 次,然后换行。例如

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

    在那之后你必须使用printChar 我会推荐 2 for loop 一一递增一递减

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

    【讨论】:

      【解决方案3】:

      一点递归解决方案:

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

      【讨论】:

        猜你喜欢
        • 2015-04-09
        • 1970-01-01
        • 1970-01-01
        • 2021-11-07
        • 2012-10-17
        • 2014-11-18
        • 1970-01-01
        • 2021-05-09
        • 1970-01-01
        相关资源
        最近更新 更多