thesaitguy2017
thesaitguy2017

Reputation: 33

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:

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

Upvotes: 0

Views: 442

Answers (2)

Bilesh Ganguly
Bilesh Ganguly

Reputation: 4141

solution:

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

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522626

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:

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

Upvotes: 1

Related Questions