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

Java 使用两个嵌套for循环和一个构造函数打印出重复模式,java,for-loop,constructor,nested-loops,Java,For Loop,Constructor,Nested Loops,我必须编写一个程序,它接受一个命令行参数n并打印出一个带有交替空格和星号的模式(如下所示)。至少使用两个嵌套for循环和一个构造函数来实现模式(下图显示了它的外观) 这是我已经尝试过的代码,没有运气。我知道如何使用单个for循环实现这一点,但不使用嵌套的for循环。我也不确定如何将构造函数与此程序集成 这就是图像的外观:*** * * * * * * * * * * * * 公共类箱{ 公共静态void main(字符串[]args){ 对于(int i=1;i我想这是一个家庭作业问题,所以我不

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

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

这就是图像的外观:***
* * * *
* * * *
* * * *
公共类箱{
公共静态void main(字符串[]args){

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

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

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

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

对Bohemian的答案稍作修改。外部for循环负责打印行。内部循环打印每行上的重复字符。构造函数只需设置
n
字段,该字段控制您打印的行数t、 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();
 } 
}
公共类框{
私有静态int n;
公用信箱(int n){
这个,n=n;
}
公共静态void doMagic(){
对于(int行=0;行
您既没有使用构造函数也没有使用命令行参数
n
。Jeffrey知道如何包含构造函数或命令行吗?我觉得这与这个问题无关。好吧,我明白您在这里的意思。这更有意义。我想奇数行应该是indented@reseter哦,我只是想你好s的格式设置是不固定的。当我想到行的一个循环和列的另一个循环时,它就更有意义了。omagic()不必是静态的。除非在测试/从主方法调用静态修饰符后忘记删除它。
* * * * 
 * * * * 
* * * * 
 * * * * 
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();
 } 
}