【问题标题】:Print out repeating pattern using two nested for loops and a constructor使用两个嵌套的 for 循环和一个构造函数打印出重复模式
【发布时间】:2012-02-12 19:48:21
【问题描述】:

我必须编写一个程序,它接受命令行参数 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(" *" + " *" + " *" + " *");

             }
         }
     }
 }

【问题讨论】:

  • 你没有使用构造函数,也没有使用命令行参数n
  • Jeffrey 知道如何包含构造函数或命令行。我觉得这与这个问题无关。

标签: java for-loop constructor nested-loops


【解决方案1】:

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

【讨论】:

  • 好的,我明白你在说什么了。这更有意义。
【解决方案2】:

对 Bohemian 的回答稍作修改。外部 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();
 } 
}

【讨论】:

  • 感谢重置者。当我想到行一个循环然后列另一个循环时,这更有意义
  • doMagic() 不必是静态的。除非您在从 main 方法测试/调用静态修饰符后忘记删除它。
【解决方案3】:

在外部 for 循环中,您可以控制要打印的行数,并选择要打印“*”还是“*”。在内部循环中,您将打印所选字符串的次数与您拥有的列数一样多。

【讨论】:

    【解决方案4】:
    • 为循环变量提供合理的名称。
    • 考虑每种类型的每次迭代应该做什么

    试试这个:

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

    输出:

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

    【讨论】:

    • 我认为奇数行应该缩进
    • @reseter 哦-我只是以为他的格式不对-固定代码
    猜你喜欢
    • 1970-01-01
    • 2021-04-09
    • 2012-09-14
    • 1970-01-01
    • 2021-03-03
    • 2018-04-04
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    相关资源
    最近更新 更多