打印三角形

时间:2017-03-26 12:49:22

标签: java methods

我在打印三角形时遇到问题。在printTriangle方法中使用2个循环语句,我必须创建一个看起来像这样的三角形。 如果用户输入3

*
**
***
**
*

在三角形方法中使用2个循环,必须使用printLine方法打印此三角形。我无法在三角形方法中打印任何内容,也无法更改line方法中的任何内容。任何有关小解释的帮助都会很棒,谢谢!

import java.util.Scanner;

public class Triangle {

    //Global declaration of the keyboard
        public static Scanner kbd = new Scanner(System.in);

    public static void main(String[] args) {
        int triSize = 0;

        System.out.println("What size triangle would you like to be printed?");
        triSize = kbd.nextInt();

        printTriangle(triSize);
    }

    /**
     * printLine is used to calculate how many asterisks should be printed
     * @param astNum the number given by the user
     * @param x is used to count the number of asterisks that have not and need to be printed
     */
    public static void printLine(int astNum){
        int x;
        for (x = 0;astNum > x; x++){
            System.out.print("*");
        }

            System.out.println("");
    }


    public static void printTriangle(int triSize){
         int x = 0;
         for (int i=1; i<=triSize; i++) {
            printLine(triSize);
          }

    }
}

2 个答案:

答案 0 :(得分:0)

添加这些循环:

for (int i=1; i<=triSize; i++) {
            printLine(i);
          }
for (int i=triSize; i>=1; i--) {
            printLine(i);
          }

答案 1 :(得分:0)

printTriangle()方法中使用两个循环来生成输出正是我将如何处理此问题。第一个循环可以从1星打印到N个星星,其中N是三角形的大小。然后,使用第二个循环打印三角形的另一半。这实际上是一种能够在两个循环中清晰表达清晰循环边界条件的练习。

public static void printTriangle(int triSize) {
    // print stars from 1 to triSize, top to bottom
    for (int i=1; i <= triSize; ++i) {
        printLine(i);
    }
    // print starts from triSize-1 to 1, from top to bottom
    // note carefully that the loop counter here begins at triSize - 1
    for (int i=triSize-1; i >= 1; --i) {
        printLine(i);
    }
}