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

Drawing a right triangle (Java) Make sure your source files are encoded in UTF-8

ID: 3593085 • Letter: D

Question

Drawing a right triangle (Java)

Make sure your source files are encoded in UTF-8. Some strange compiler errors are due to the text encoding not being correct.

This program will output a right triangle based on user-specified height and symbol.

Write a program to use a nested loop to output a right triangle of a user entered height. The program prompts the user for the character to use, such as % or * and the triangle height. The program uses nested loops to output the triangle as shown.

Example output for triangleChar = % and triangleHeight = 5.

The first line will have one user-specified character, such as % or *. Each subsequent line will have one additional user-specified character until the number in the triangle's base reaches height. Output a space after each user-specified character, including after the line's last user-specified character. The example run is shown as it looks in the Eclipse Console window which includes both output and input. Each input ends with newline which means there is an extra newline before the triangle begins. The last line of the triangle ends with a newline (Which this presentation tool removes, unfortunately). If you would like help comparing the output above with Eclipse output Diff Checker can be helpful. Copy the example above, adding the newline at the end, then compare to your Eclipse Console output.

The user is required to keep entering values until the value is between 1 and 10, inclusive of both.

Explanation / Answer

DrawRightTriangle.java

import java.util.Scanner;

public class DrawRightTriangle {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

char triangleChar = '-';

int triangleHeight = 0;

System.out.println("Enter a character: ");

triangleChar = scnr.next().charAt(0);  

System.out.println("Enter triangle height: ");

triangleHeight = scnr.nextInt();

for(int i=0; i<triangleHeight; i++){

for(int j=0; j<=i; j++){

System.out.print(triangleChar);

}

System.out.println();

}

return;

}

}

Output:

Enter a character:
%
Enter triangle height:
5
%
%%
%%%
%%%%
%%%%%

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