3) Write a program that presents the user a menu of four choices, \"Cirdle\",Isq
ID: 3754302 • Letter: 3
Question
3) Write a program that presents the user a menu of four choices, "Cirdle",Isquare", "Rectangle", and "Exit" to calculate the area of one of these geometric objects. Once a choice is made, the program would ask the user for the data required to do the calculation. For example, if the user input were "Circle", the program would prompt the user to enter the value of the radius of the circle. Implement a solution using only IF statements. 4) Rewrite your solution to Exercise 3 using a SWITCH statement this time.Explanation / Answer
[A] Using IF ELSE :
import java.util.Scanner;
public class AreaCalculator
{
public static void main(String args[])
{
int input = 0;
double len, bre, peri, area;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Choice");
System.out.println("1. Circle");
System.out.println("2. Square");
System.out.println("3. Rectangle");
System.out.println("4. Exit");
input = scanner.nextInt();
if(input == 1 ) {
System.out.println("Enter the radius:");
double r= scanner.nextDouble();
area=(22*r*r)/7 ;
System.out.println("Area of Circle is: " + area);
}else if(input == 2) {
System.out.println("Enter Side of Square:");
double side = scanner.nextDouble();
area = side*side;
System.out.println("Area of Square is: "+area);
}else if(input == 3) {
System.out.print("Enter Length and Breadth of Rectangle : ");
len = scanner.nextInt();
bre = scanner.nextInt();
area = len*bre;
System.out.print("Area = " +area);
}
}
}
---------------------------------------------------------------------------------------------------------
[B] Using Switch statement
package com.steepgraph.datamigration.process;
import java.util.Scanner;
public class AreaCalculator
{
public static void main(String args[])
{
int input = 0;
double len, bre, peri, area;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Choice");
System.out.println("1. Circle");
System.out.println("2. Square");
System.out.println("3. Rectangle");
System.out.println("4. Exit");
input = scanner.nextInt();
switch(input) {
case 1 :
System.out.println("Enter the radius:");
double r= scanner.nextDouble();
area=(22*r*r)/7 ;
System.out.println("Area of Circle is: " + area);
break;
case 2 :
System.out.println("Enter Side of Square:");
double side = scanner.nextDouble();
area = side*side;
System.out.println("Area of Square is: "+area);
break;
case 3 :
System.out.print("Enter Length and Breadth of Rectangle : ");
len = scanner.nextInt();
bre = scanner.nextInt();
area = len*bre;
System.out.print("Area = " +area);
break;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.