JAVA-9
Q.9 Write a Java program that prompts the user to input the base and height of a triangle. Accordingly calculates and displays the area of a triangle using the formula (base* height) / 2, and handles any input errors such as non-numeric inputs or negative values for base or height. Additionally, include error messages for invalid input and provide the user with the option to input another set of values or exit the program.
Solution :-Â
import java.util.*;
public class TriangleAreaCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean continueInput = true;
while (continueInput) {
try {
System.out.print("Enter the base of the triangle: ");
double base = Double.parseDouble(scanner.nextLine());
System.out.print("Enter the height of the triangle: ");
double height = Double.parseDouble(scanner.nextLine());
if (base <= 0 || height <= 0) {
System.out.println("Error: Base and height must be positive numbers.");
continue;
}
double area = (base * height) / 2;
System.out.println("The area of the triangle is: " + area);
} catch (NumberFormatException e) {
System.out.println("Error: Please enter valid numeric values for base and height.");
}
System.out.print("Do you want to calculate again? (yes/no): ");
String response = scanner.nextLine().trim().toLowerCase();
if (!response.equals("yes")) {
continueInput = false;
}
}
System.out.println("Program terminated.");
scanner.close();
}
}