I have to write a program that takes a command-line argument n and prints out a pattern with alternating spaces and asterisks (as demonstrated below). Use at least two nested for loops and a constructor to achieve the pattern (an image is shown below of how it’s suppose to look).
This is the code I have tried already and no luck. I understand how to do this with a single for loop, but not a nested. I am also unsure how to integrate a constructor with this program.
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(" *" + " *" + " *" + " *");
}
}
}
}
Slight modification to Bohemian’s answer. The outer for-loop is responsible for printing the rows. The inner loop prints the repeated characters on each row. The constructor simply sets the
nfield, which controls how many rows you print out. The main method creates a new object and invokes its only method.