Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Triangle Pattern Write a program that reads in lines from the input. Each l

ID: 3806543 • Letter: J

Question

Java

Triangle Pattern

Write a program that reads in lines from the input. Each line has a single integer followed by a single character. The objective is to print a triangle pattern using the input character. The first integer represents the number of rows of the triangle. Input values will contain only integers greater than or equal to 1 and less than or equal to 50.

Input

The format of an input line is noRows char The first is an integer (and can be read using nextInt()). The last one is a single character (like *) and can be read using next() as a String and then using charAt(0) to get at the first character.

Output

For each line of input, a triangular pattern is printed consisting of several rows. If the no of rows is less than or equal to zero or more than 50, the program prints out an error statement as shown in the sample output.

Sample Input

2 *

-1 '

10 =

Sample Output

*

* *

error in input

=

==

===

====

=====

======

=======

========

=========

==========

HINT

1. use in.next().charAt(0) to get the character.

2. don’t forget to discard the rest of the input line using in.nextLine() if you are using in.hasNextLine() to check if there is a next line.

3. You will need two loops for this one as well.

The outputs need to be spot on or it will not pass my online submission (CYOJ) Thanks.

Explanation / Answer

import java.util.Scanner;
public class Triangle{

public static void main(String []args){
  
       Scanner scanner = new Scanner(System.in);
      
       while ( scanner.hasNextLine())
       {
           int num = scanner.nextInt();
           String str = scanner.next();
           char chr = str.charAt(0);
           if (num>0 && num <=50)
           {
                   for(int i=0;i<=num-1;i++)
                   {
                       for(int j=0;j<i+1;j++)
                       {
                       System.out.print(chr);
                       }
                   System.out.println();
                   }
           }
          
           else
           {
               System.out.println("error in input");
           }
      
       }      

}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote