77.0k views
5 votes
Write an interactive Java Program named HollowRightAngled Triangle.java which uses the JOptionPane class for input. The program should ask you to input a character of your choice, as well as the height/Depth of the Triangle. The character can be any character, e.g., a star, an integer, a letter of the alphabet, a $ sign, etc. When the character has been entered by the user, the program should echo using the System.out.println() output scheme, the words, "You have Entered The Character, according to the character entered. After that, the program should ask you to enter a depth/height. Once the height/depth has been entered, the pogram should then draw/output a right-angled triangle made of the chosen character .​

1 Answer

1 vote

Here is a Java program to draw a hollow right angled triangle:

import javax.swing.JOptionPane;

public class HollowRightAngledTriangle {

public static void main(String[] args){

String character = JOptionPane.showInputDialog(null, "Enter a character: ");

System.out.println("You have entered the character " + character);

String height = JOptionPane.showInputDialog(null, "Enter height: ");

int h = Integer.parseInt(height);

for (int i = 1; i <= h; i++) {

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

if (j == 1 || i == h || i == j){

System.out.print(character);

}

else {

System.out.print(" ");

}

}

System.out.println();

}

}

How it works:

  • We use JOptionPane to promt the user for input.
  • We store the character in the String character.
  • We store the height in the String height and parse it to an int.
  • We use two nested for loops.
  • The outer loop iterates over the height.
  • The inner loop iterates over i , the current height.
  • We print the character if j (the inner loop counter) is 1 (first element in row)
  • or if i is equal to h (last row) or if i equals j (last element in row).
  • Otherwise we print a space.
  • After the inner loop, we go to the next line.
User Jonathan Meguira
by
7.9k points