Home > Software design >  Making a specific pattern in Java
Making a specific pattern in Java

Time:11-04

How do I make this pattern using a input from the user? input=3

(1st line) (2nd line)-- (third line)

I have tried using the for loops but just couldn't figure out how to get it to work.

CodePudding user response:

First, we can judge the parity of a value by taking the remainder of 2

    get the input value;
    loop i = 1 & i <= input value:
       when i is odd output char is " " 
       when i is even  output char is "-" 
       loop j = 0 & j < i
            print i times output char

code:

    int inputVal = 3;
    for (int i = 1; i <= inputVal; i  ) {
        String outputTag = i % 2 == 0 ? "-" : " ";
        for (int j = 0; j < i; j  ) {
            System.out.print(outputTag);
        }
        System.out.println();
    }

CodePudding user response:

        Scanner inp = new Scanner(System.in);
        System.out.println("Enter Input");

        int input = inp.nextInt();

        for (int i = 0; i < input; i  ) {
            String symbol = i%2 == 0 ? '-' : ' ';
            for (int j = 0; j < i; j  ) {
                System.out.print(symbol);
            }

            System.out.print("line"   (i 1)   "\t");
        }
  •  Tags:  
  • java
  • Related