使用循环向字符串添加空格

Add spaces to string with loop

我想通过循环获得这个输出。但是用户需要在运行时定义该值。因此,当用户输入 6 时,结果应该是这样的(注意创建了 6 行!字符之间的空格递增):

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

到目前为止,我已经编写了代码,但对于如何添加空格真的很困惑。目前的代码如下所示:

import java.util.*;

public class 模式 {

public static void main(String[] args)
{

    int input;
    Scanner kb = new Scanner(System.in);    

    System.out.print("Enter a positive number: ");
    input = kb.nextInt();

    while (input <= 0)
    {
        System.out.print("That isn't positive, try again: ");
        input= kb.nextInt();
    }

    for (int number = 0; number < input; number++)
    {
        System.out.print("#");

您想要的是打印与当前行号 - 1 相等的空格数。因此您必须为此创建一个 for 循环。

import java.util.*;

public class Pattern
{

    public static void main(String[] args)
    {

        int input;
        Scanner kb = new Scanner(System.in);    

        System.out.print("Enter a positive number: ");
        input = kb.nextInt();

        while (input <= 0)
        {
            System.out.print("That isn't positive, try again: ");
            input= kb.nextInt();
        }

        for (int number = 0; number < input; number++)
        {
            System.out.print("#");

            //print spaces equal to the number variable
            for(int count = 0; count < number; count++)
            {
                System.out.print(" ");
            }

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

    }

}

我就把它留在这里,以防你也想要 JDK 1.8 解决方案:)

int lineCount = // read from console

String result = IntStream.range(0, lineCount)
    .mapToObj(i -> 
         Stream.generate(() -> " ")
               .limit(i)
               .collect(Collectors.joining())
    )
    .map(s -> "#" + s + "#")
    .collect(Collectors.joining("\n"));

System.out.println(result);