简体   繁体   English

如何在Java中使用循环制作模式

[英]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. 您错误地调用了System.out.println()作为第一个哈希标记,该标记在不需要的位置打印了换行符。 Just change that call to System.out.print() and you should be good to go: 只需将该调用更改为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("#");
         }
     }
}

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("#"); 您需要更改第一个System.out.println("#"); to System.out.print("#"); 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)
                );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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