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.