In: Computer Science
Below is your working code: -
/*
Writing a program that displays the following:
calculating area of a circle, calculating area of a rectangle,
calculating area of a triangle, and quit.
*/
import java.text.DecimalFormat;
import java.util.Scanner;
public class GeoCalculator {
public static void main(String arg[]) {
char selection;
Scanner get = new
Scanner(System.in); // having user input
DecimalFormat twoDigits = new
DecimalFormat("0.00"); // formatting area
// to two
// decimal
// places
boolean done = false;
// display choice of
selection
System.out.println("Geometry
Calculator");
System.out.println("Please select
from the following menu:");
System.out.println("1. Calculate
the Area of a Cirlce.");
System.out.println("2. Calculate
the Area of a Rectangle.");
System.out.println("3. Calculate
the Area of a Triangle.");
System.out.println("4.
QUIT");
boolean error = false;
// checking if selection is
between 1 and 4
while (!done) {
if(!error)
{
System.out.println("Please make a selection:
");
}
selection =
get.next().charAt(0);
// output of
selection made
switch
(selection) {
case '1': //
getting area of circle
error = false;
System.out.println("Please enter the circle's
radius: ");
double r = get.nextDouble();
double areac = 3.14159 * r * r;
System.out.printf("Area of Circle is: "
+
twoDigits.format(areac) + "\n");
break;
case '2': //
getting area of rectangle
error = false;
System.out.printf("Please enter the length:
");
double l = get.nextDouble();
System.out.printf("Please enter the width:
");
double w = get.nextDouble();
double arear = l * w;
System.out.printf("Area of Rectangle is: "
+
twoDigits.format(arear) + "\n");
break;
case '3': //
getting area of triangle
error = false;
System.out.printf("Please enter the base:
");
double b = get.nextDouble();
System.out.printf("Please enter height:
");
double h = get.nextDouble();
double areat = b * h * 0.5;
System.out.printf("Area of Triangle is: "
+
twoDigits.format(areat) + "\n");
break;
case '4': //
no option
System.out.printf("QUIT");
error = false;
done = true;
break;
default:
error = true;
System.out.println("Try again. Please make a
selection (1-4)");
break;
}
}
}
}
Output
Geometry Calculator
Please select from the following menu:
1. Calculate the Area of a Cirlce.
2. Calculate the Area of a Rectangle.
3. Calculate the Area of a Triangle.
4. QUIT
Please make a selection:
7
Try again. Please make a selection (1-4)
-2
Try again. Please make a selection (1-4)
1
Please enter the circle's radius:
2
Area of Circle is: 12.57
Please make a selection:
2
Please enter the length: 2
Please enter the width: 5
Area of Rectangle is: 10.00
Please make a selection:
3
Please enter the base: 5
Please enter height: 2
Area of Triangle is: 5.00
Please make a selection:
4
QUIT