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

时间:2015-05-04 07:42:08

标签: java for-loop spacing

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

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

到目前为止,我已经编写了代码,并且对于如何添加空格感到很困惑。到目前为止,代码看起来像这样:

import java.util.*;

公共类模式 {

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("#");

2 个答案:

答案 0 :(得分:2)

你想要的是打印一些相当于当前行号的空格--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("#");
        }               

    }

}

答案 1 :(得分:0)

我将此留在此处,以防您需要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);