我想用“*”绘制一个矩形

时间:2015-03-30 10:37:00

标签: java

当我在eclipse中运行这个程序时,我得到的输出显示一个矩形,一列有5颗星,连续有5颗星。它应该是一列中的5星和行中的2星。我的代码出了什么问题?

public class printing {

    public static void main(String[] args) {

//      printStars(5);
//      printStars(3);
//      printStars(9);
//      printStars(4);
//      printSqare(4);
        printRectangle(5,2);

    }
    private static void printStars(int amount) {
         int i = 0;
            while ( i < amount ) {
                System.out.print("*");
                i++;
         }
            System.out.println("\n");
    }

//  private static void printSqare(int sidesize){
//      int c= 0;
//      while (c < sidesize){
//          printStars(sidesize);
//          c++;
//      }
//      System.out.println("\n");
//  } 



private static void printRectangle(int width, int height) {

    int num1=0;
    for (int num2=1; num2<height; num2++){
        while (num1 < width ){
        printStars(width);
        num1++;
            }   
        }       
    }
}

2 个答案:

答案 0 :(得分:3)

您评论的printSquare方法实际上很好,您可以重复使用printRectangle的算法! 这里只需要一个循环,所以

private static void printRectangle(int width, int height) {
    int num1=0;
    while (num1 < height ){
        printStars(width);
        num1++;      
    }       
}

private static void printRectangle(int width, int height) {
    for (int num1 = 0; num1 < height; num1++ ){
        printStars(width);     
    }       
}

在当前代码中,您输入for循环,然后在printStars循环中调用while。但是,while循环5次而不是2次,因为条件为num1 < width(而不是num1 < height)。然后,for第二次循环并且什么都不做(因为num1大于width)。

答案 1 :(得分:0)

您可以更改

之类的printRectangle方法
private static void printRectangle(int width, int height) {

    for (int num2 = 0; num2 < height; num2++) {
            printStars(width);
    }
}

我把你的问题读成有5 * 2的矩形。不确定它是否正确解释。

相关问题