使用两个嵌套的for循环和一个构造函数打印出重复模式



我必须编写一个程序,该程序接受命令行参数n,并打印出一个带有交替空格和星号的模式(如下所示)。至少使用两个嵌套的for循环和一个构造函数来实现模式(下面显示了它的外观)。

这是我已经尝试过的代码,但没有成功。我知道如何使用单个for循环来实现这一点,但不使用嵌套循环。我也不确定如何将构造函数与这个程序集成

This is how the image should look: * * * *
                                    * * * *
                                   * * * *
                                    * * * *
public class Box {
     public static void main(String[] args) {
         for (int i=1; i<2; i++) {
             System.out.println("* " + "* " + "* " + "* ");
             for (int j=0; j<i; j++) {
                 System.out.print(" *" + " *" + " *" + " *");
             }
         }
     }
 }

我想这是一个家庭作业问题,所以我不会给你任何代码:)你的问题是打印出一整行,包括外循环和内循环。使用外循环绘制每一行,使用内循环绘制每行中的每个星号。因此,外循环用于行,内循环用于列。

对波希米亚人的回答稍作修改。外部for循环负责打印行。内部循环在每一行打印重复的字符。构造函数只需设置n字段,该字段控制打印出的行数。main方法创建一个新对象并调用其唯一的方法。

public class Box {
private static int n; 
public Box(int n){
    this.n = n;
}
public static void doMagic() {
    for (int row = 0; row < n; row++) {
        if(row%2==1)
            System.out.print(" ");
        for (int col = 0; col < n; col++) {
            System.out.print("* ");
        }
        System.out.println();
    }
}
   public static void main(String[] args) {
    new Box(4).doMagic();
 } 
}

在外部for循环中,您可以控制要打印的行数,并选择要打印"*"还是"*"。在内部循环中,您将打印所选字符串的列数。

  • 为循环变量指定合理的名称
  • 思考每种类型的每次迭代应该做什么

试试这个:

public static void main(String[] args) {
     for (int row = 0; row < 4; row++) {
         // Not sure if you really meant to indent odd rows. if not, remove if block
         if (row % 2 == 1) {
            System.out.print(" "); 
         }
         for (int col = 0; col < 4; col++) {
             System.out.print("* ");
         }
         System.out.println();
     }
 }

输出:

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

最新更新