我有这段代码,它将根据用户输入的形状找到不同形状的区域。问题是如何从主类获取输入的测量值(例如长度、宽度)到圆形、三角形、矩形和方形类?这是我的代码。
import java.lang.Math;
import java.util.Scanner;
import java.text.DecimalFormat;
class Circle{
double radius;
void CircleMeasurement(){
radius = r;
}
double getCircleArea(){
return(Math.PI*Math.pow(radius,2));
}
}
class Triangle{
int base, height;
void TriangleMeasurement(){
base = b;
height = h;
}
int getTriangleArea(){
return((base*height)/2);
}
}
class Rectangle{
int length, width;
void RectangleMeasurement(){
length = l;
width = w;
}
int getRectangleArea(){
return(length*width);
}
}
class Square{
int sides;
void SquareMeasurement(){
sides = s;
}
int getSquareArea(){
return( sides * sides);
}
}
class Shapes{
public static void main(String[] args){
String key;
double r;
int b, h, l, w, s;
System.out.println("Welcome!");
System.out.println("Choose your option:");
System.out.println("1 - Circle, 2 - Triangle, 3 - Rectangle, 4 - Square");
Scanner in = new Scanner(System.in);
key = in.nextLine();
if (key=="1" || key =="circle"){
System.out.println("Area for Circle");
System.out.println("Enter radius:");
Scanner.in = new Scanner(System.in);
r = in.nextInt;
Circle circle1 = new Circle();
System.out.println("The area is equal to" + circle1.getCircleArea());
}
else if (key == "2"){
System.out.println("Area for Triangle");
System.out.println("Enter base:");
Scanner.in = new Scanner(System.in);
b = in.nextInt;
System.out.println("Enter height:");
h = in.nextInt;
Triangle triangle1 = new Triangle();
System.out.println("The area is equal to" + triangle1.getTriangleArea());
}
else if (key == "3"){
System.out.println("Area for Rectangle");
System.out.println("Enter length:");
Scanner.in = new Scanner(System.in);
l = in.nextInt;
System.out.println("Enter width:");
w = in.nextInt;
Rectangle rectangle1 = new Rectangle();
System.out.println("The area is equal to" + rectangle1.getRectangleArea());
}
else if (key == "4"){
System.out.println("Area for Square");
System.out.println("Enter side:");
Scanner.in = new Scanner(System.in);
s = in.nextInt;
Square square1 = new Square();
System.out.println("The area is equal to" + square1.getSquareArea());
}
}
}