logo

Java Code import java.util.Scanner; /** * * File name

Write a Java program for calculating the area of triangles and rectangles. The user is asked whether a triangle or rectangle is required, then prompted for the relevant dimensions, and the answer is displayed. Use Note that the area of a rectangle is width * height, and the area of a triangle is ½ base width * height. Ensure your program works correctly for different user inputs.

2 Pages257 Words314 Views
   

Added on  2023-04-08

Java Code import java.util.Scanner; /** * * File name

Write a Java program for calculating the area of triangles and rectangles. The user is asked whether a triangle or rectangle is required, then prompted for the relevant dimensions, and the answer is displayed. Use Note that the area of a rectangle is width * height, and the area of a triangle is ½ base width * height. Ensure your program works correctly for different user inputs.

   Added on 2023-04-08

ShareRelated Documents
Java Code
import java.util.Scanner;
/**
*
* File name :AreaCalculator.java
* Date :16-Mar-2019
* Time :7:05:45 PM
*/
public class AreaCalculator {
private static Scanner sc;
public static void main(String[] args) {
sc=new Scanner(System.in);
String figure=getFigure();
System.out.print("\nEnter the height for the "+figure+": ");
double height=readDouble();
if(figure.equals("rectangle"))
{
System.out.print("Enter the width for the "+figure+": ");
double width=readDouble();
System.out.println("\n\nArea of the Rectangle is
"+height*width);
}
else
{
System.out.print("Enter the base width for the "+figure+": ");
double width=readDouble();
System.out.println("\n\nArea of the Triangle is
"+String.format("%.2f",0.5*height*width));
}
}
/**
* Read a positive decimal value and it should be greater than 0
* @return the read decimal value
*/
private static double readDouble() {
try
{
double val=Double.parseDouble(sc.nextLine());
if(val<=0)
throw new Exception();
return val;
}
catch(Exception e)
{
System.out.print("\nPlease enter a positive decimal value
(Greater than 0) : ");
return readDouble();
}
}
/**
* Read a positive integer and it should be greater than 0
* @return the read integer
*/
private static int getInt()
Java Code import java.util.Scanner; /** * * File name_1

End of preview

Want to access all the pages? Upload your documents or become a member.

Related Documents
import java.util.Scanner; public class rectangle { private
|2
|241
|184

Design Documentation Pseudo Code BEGIN Display Welcome message BEGIN
|13
|1512
|68

JAVA Program Using Array of Objects
|28
|2144
|15

Java Assignment Help | Online Homework
|13
|1219
|353

Vehicle Data Inventory System
|18
|2151
|53

CarYardMIT162011 Class Implementation in Java
|6
|1107
|393