简体   繁体   中英

how to make a pattern with loops in java

public class NestedLoopPattern {
    public static void main(String[] args) {
        final int HASHTAG_AMMOUNT = 6;

        for (int i=0; i < HASHTAG_AMMOUNT; i++) {
            System.out.println("#");
            for (int j=0; j < i; j++) {
                System.out.print(" ");
            }
            System.out.println("#");
        }
    }
}

I am supposed to make this pattern with nested loops, however with the code above I can't,

##
# #
#  #
#   #
#    #
#     #

I just keep getting this as my output:

#
#
#
 #
#
  #
#
    #
#
      #
#
         #

You erroneously were calling System.out.println() for the first hash mark, which was printing a newline where you don't want it. Just change that call to System.out.print() and you should be good to go:

 public class NestedLoopPattern {
     public static void main(String[] args) {
         final int HASHTAG_AMMOUNT = 6;

         for (int i=0; i < HASHTAG_AMMOUNT; i++) {
             // don't print a newline here, just print a hash
             System.out.print("#");
             for (int j=0; j < i; j++) {
                 System.out.print(" ");
             }
             System.out.println("#");
         }
     }
}

Output:

##
# #
#  #
#   #
#    #
#     #

The problem is that on each iteration of the outer loop, you're printing two newlines. So you print the first "#", then a newline, then the rest of the line.

You need to change the first System.out.println("#"); to System.out.print("#"); , and then it will work.

So you should change your code to this:

public class NestedLoopPattern {
    public static void main(String[] args) {
        final int HASHTAG_AMMOUNT = 6;

        for(int i = 0; i < HASHTAG_AMMOUNT; i++) {
             System.out.print("#"); //No need to print a newline here

             for(int j = 0; j < i; j++) {
                 System.out.print(" ");
             }

             System.out.println("#");
         }
     }
}

And that will give you the expected output:

##
# #
#  #
#   #
#    #
#     #

solution:

IntStream.rangeClosed(1, MAX)
                .forEach(i -> IntStream.rangeClosed(1, i + 1)
                        .mapToObj(j -> j == i + 1 ? "#\n" : j == 1 ? "# " : "  ")
                        .forEach(System.out::print)
                );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM