Write a Java program that can calculate and print out the area of a circle. The user enters data of the radius and its measurement unit ("in" for inch, "ft" for feet, "cm" for centimeter, and "m" for meter) from the console. The program should check to be sure that the radius is not negative and the measurement unit must be one among the listed-above units.

Respuesta :

Answer:

// program in java.

// package

import java.util.*;

// class definition

class Main

{

   // main method of the class

public static void main (String[] args) throws java.lang.Exception

{

   try{

  // Scanner object to read input

Scanner scr=new Scanner(System.in);

 // variables

double rad;

String unit1="in";

String unit2="ft";

String unit3="cm";

String unit4="m";

// ask user to enter radius

System.out.print("Enter the radius: ");

 // read radius

rad=scr.nextDouble();

 // check radius is negative or not

while(rad<0)

{

    System.out.println("Radius can't be negative:");

     // ask again to enter radius

    System.out.print("Enter the Radius again:");

     // read radius again

    rad=scr.nextInt();

}

// ask user to enter the unit of measurement

System.out.print("Enter the unit (\"in\" for inch, \"ft\" for feet, \"cm\" for centimeter, and \"m\" for meter):");

 // read unit

 String unt=scr.next();

 // calculate area

double area=3.14*rad*rad;

 // print area and unit

if(unt.equals(unit1))

    System.out.println(area+" inch.");

else if(unt.equals(unit2))

    System.out.println(area+" feet.");

else if(unt.equals(unit3))

    System.out.println(area+" centimeter.");

else if(unt.equals(unit4))

    System.out.println(area+" meter.");

   }catch(Exception ex){

       return;}

}

}

Explanation:

Read radius of circle from user with Scanner object and assign it to variable "rad".Check the radius is negative or not.If the radius is negative ask user to enter radius again until user enters a positive radius.Then read the unit of measurement.calculate the area of circle and print area with unit.

Output:

Enter the radius: -4

Radius can't be negative:

Enter the Radius again:6

Enter the unit ("in" for inch, "ft" for feet, "cm" for centimeter, and "m" for meter):cm

Area of circle is 113.03999999999999 centimeter.

RELAXING NOICE
Relax