[英]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("#");
}
}
}
我应该使用嵌套循环来制作这种模式,但是使用上面的代码我做不到,
##
# #
# #
# #
# #
# #
我只是不断得到这个作为我的输出:
#
#
#
#
#
#
#
#
#
#
#
#
您错误地调用了System.out.println()
作为第一个哈希标记,该标记在不需要的位置打印了换行符。 只需将该调用更改为System.out.print()
,您应该可以进行以下操作:
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("#");
}
}
}
输出:
##
# #
# #
# #
# #
# #
问题在于,在外循环的每次迭代中,您都在打印两条换行符。 因此,您将打印第一个“#”,然后打印换行符,然后打印其余行。
您需要更改第一个System.out.println("#");
到System.out.print("#");
,然后它将起作用。
因此,您应该将代码更改为此:
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("#");
}
}
}
这将为您提供预期的输出:
##
# #
# #
# #
# #
# #
java8解决方案:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.rangeClosed(1, i + 1)
.mapToObj(j -> j == i + 1 ? "#\n" : j == 1 ? "# " : " ")
.forEach(System.out::print)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.