Java Program for Area Calculation: Rectangle and Triangle Shapes

Verified

Added on  2023/04/08

|2
|267
|54
Homework Assignment
AI Summary
This Java program calculates the area of either a triangle or a rectangle based on user input. The program prompts the user to select a shape (triangle or rectangle) and then enter the width and height. It uses the `JOptionPane` class for input and output dialogs. The `calculatearea` method determines the area based on the shape selected. Error handling is included to check for invalid inputs, such as negative dimensions or incorrect shape selections, displaying appropriate warning messages. Finally, the program displays the calculated area or an error message to the user, ensuring a robust and user-friendly experience. Desklib provides this solution and many other solved assignments for students.
Document Page
import javax.swing.JOptionPane; // Dialog box methods
public class rectangle {
public static void main(String[] args)
{
double shape = InputDouble("Area of \n 1. Triangle \n 2.
Retangle"); /* User choice for shape*/
double width = InputDouble("Enter Width"); /* user value for
width */
double height = InputDouble("Enter Height"); /* user value for
height */
double shapearea = calculatearea(width, height, shape); /*
variable to store the value of the calculated area */
if (shapearea == 0) /* value returned if width/height was entered
as 0 or triangle/rectangle was not selected 8 */
{
JOptionPane.showMessageDialog(null, "The value entered was
incorrect \n Please re assess the entered criteria"); /* Display warning
message */
}
else if (shapearea < 0) /* value is a negative number was entered
for dimension */
{
JOptionPane.showMessageDialog(null, "A negative value has
been entered. An area can never be negative. Please try again"); /* Display
warning message */
}
else {JOptionPane.showMessageDialog(null, "The area is"
+ shapearea);} /* Return the area of the shape*/
System.exit(0); // Terminate program
}
public static double InputDouble(String prompt)
{
/* Get data in string form: convert to double */
String s = JOptionPane.showInputDialog(prompt);
return Double.parseDouble(s);
}
public static double calculatearea(double Basewidth, double tall,
double Typeshape )
{
/* Calculates the area */
double test;
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
if (Typeshape == 1.0)
{test = ((Basewidth * .5) * tall); /* Calculate the area if the object
is a triangle*/
}
else if (Typeshape == 2.0) {
test = (Basewidth * tall); /* Calculate the area if the object is
a rectangle*/
}
else {
test = 0; /*error handling */
}
return test;
}
}
chevron_up_icon
1 out of 2
circle_padding
hide_on_mobile
zoom_out_icon
[object Object]