Reputation: 33
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
Reputation: 4141
java8 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
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