110k views
1 vote
write a java program that asks the user to choose from 4 shapes (triangle, circle, rectangle, rhombus), next calculate the area of the shape the user chose and display the name of the shape chosen, the input data for the shape, and the area. include a quit or continue statement for the user. use a loop

User Asnad Atta
by
8.4k points

1 Answer

3 votes

Final answer:

The Java program provided requests the user to choose from four shapes, calculates the area, displays the shape's name, input data, and area, and allows the user to quit or continue with another input.

Step-by-step explanation:

Here is a simple Java program that fulfills your assignment of asking a user to choose from 4 shapes (triangle, circle, rectangle, rhombus), calculating the area of the chosen shape, and displaying the relevant information to the user:

import java.util.Scanner;

class ShapeAreaCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String shape;
double area = 0;
boolean continueCalculating = true;

while(continueCalculating) {
System.out.println("Choose a shape (triangle, circle, rectangle, rhombus) or type 'quit' to exit:");
shape = scanner.next();

switch (shape.toLowerCase()) {
case "triangle":
System.out.println("Enter base and height:");
double base = scanner.nextDouble();
double height = scanner.nextDouble();
area = 0.5 * base * height;
break;
case "circle":
System.out.println("Enter radius:");
double radius = scanner.nextDouble();
area = Math.PI * radius * radius;
break;
case "rectangle":
System.out.println("Enter length and width:");
double length = scanner.nextDouble();
double width = scanner.nextDouble();
area = length * width;
break;
case "rhombus":
System.out.println("Enter diagonals p and q:");
double diagonal1 = scanner.nextDouble();
double diagonal2 = scanner.nextDouble();
area = (diagonal1 * diagonal2) / 2;
break;
case "quit":
continueCalculating = false;
break;
default:
System.out.println("Invalid shape!");
}

if(continueCalculating) {
System.out.println("The " + shape + " has an area of " + area);
}
}
scanner.close();
System.out.println("Program ended.");
}
}

This program uses a loop to repeatedly ask a user to choose a shape or exit the program. It processes the user's input to calculate the area for the selected shape and displays the result. The user has the option to quit or continue with fresh input by typing 'quit' when prompted for the shape choice.

User Kiwidrew
by
8.9k points