Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

java - Display squares of asterisks, filled and hollow, side by side

I'm currently trying to display a filled asterisk square and a hollow asterisk :

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

Instead, I'm getting this output:

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

I'm not so sure how to make it side by side instead of up and down. Do I have to put the hollow nested loop inside the filled loop or do I have to do something else? Here is my code:

public class doubleNestedLoops {
    public static void main(String[] args) {
        //Filled Square
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 10; j++) {
                System.out.print("*");
            }
            System.out.println();
        }

        //Hollow Square
        for (int j = 1; j <= 5; j++) {
            for (int i = 1; i <= 10; i++) {
                if (j == 1 || j == 5 || i == 1 || i == 10) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After you print a line, you cannot go back to the line that was printed and add more * to it. This means that after you print a line for the filled square, you can't go back to the same line that was already printed to add the *s for the hollow square.

The easiest way to resolve this is to restructure your code a bit so that instead of printing first the filled square and the hollow one afterwards, you print both at the same time on each line.

To do this, you could restructure your code to something like this:

//Loop through each line that needs to be printed
for(int i = 1; i <= 5; i++){

   //Loop through characters for filled square needed in this line
   for(int j=0; j< ; j++){
       //Add print logic for filled square
   }

   //Loop through characters for hollow square on the same line
   for(int j=1; j<=5; j++){
       //Add print logic for hollow square
   }

   System.out.println();//Go to next line
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...