-2

I want to get this output via loops. However user needs to define the value when it runs. So, when the user inputs 6, the result should be this(notice 6 rows are created! with incrementing spaces between the characters):

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

I have wrote the code so far and am really confused as to how to add spaces.. The code so far looks like this :

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("#");
BTurk7575
  • 25
  • 1
  • 1
  • 6

2 Answers2

2

The thing you want is to print a number of spaces that is equivalent to the current line number - 1. So you'll have to create a for loop for that.

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

    }

}
moffeltje
  • 4,521
  • 4
  • 33
  • 57
0

I just leave this here, in case you want a JDK 1.8 solution too :)

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);
Balázs Édes
  • 13,452
  • 6
  • 54
  • 89