Java输出一组图形的面积和、周长和,其中图形具备以下特征:圆形:半径;正方形形:边长;三角形:三条边长;输出内容如图:输出内容如图:
时间: 2024-10-29 07:19:29 浏览: 13
area_calculator:计算圆形,正方形,矩形和三角形的面积
5星 · 资源好评率100%
在Java中,我们可以分别创建圆形、正方形和三角形的类,并计算每个图形的面积、周长。然后,在主程序中,我们让用户输入对应的属性(圆的半径、正方形的边长或三角形的三边长),根据用户的选择来实例化相应的图形并计算其面积和周长。
以下是简化版的代码示例:
```java
import java.util.Scanner;
class Circle {
double radius;
double area, circumference;
public Circle(double r) {
radius = r;
area = Math.PI * radius * radius;
circumference = 2 * Math.PI * radius;
}
// 输出面积和周长
public void printStats() {
System.out.println("Circle (radius=" + radius + "):");
System.out.printf("Area: %.2f\n", area);
System.out.printf("Circumference: %.2f\n", circumference);
}
}
class Square {
double side;
double area, perimeter;
public Square(double s) {
side = s;
area = side * side;
perimeter = 4 * side;
}
// 输出面积和周长
public void printStats() {
System.out.println("Square (side=" + side + "):");
System.out.printf("Area: %.2f\n", area);
System.out.printf("Perimeter: %.2f\n", perimeter);
}
}
class Triangle {
double a, b, c; // 任意两边长度
double area, perimeter;
// 提供构造函数接收三边长度
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
perimeter = a + b + c;
double s = perimeter / 2; // 半周长
area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
// 输出面积和周长
public void printStats() {
System.out.println("Triangle (a=" + a + ", b=" + b + ", c=" + c + "):");
System.out.printf("Area: %.2f\n", area);
System.out.printf("Perimeter: %.2f\n", perimeter);
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose the shape to calculate:");
System.out.println("1. Circle");
System.out.println("2. Square");
System.out.println("3. Triangle");
int choice = scanner.nextInt();
switch (choice) {
case 1:
double circleRadius = scanner.nextDouble();
Circle circle = new Circle(circleRadius);
circle.printStats();
break;
case 2:
double squareSide = scanner.nextDouble();
Square square = new Square(squareSide);
square.printStats();
break;
case 3:
double triangleA = scanner.nextDouble(), triangleB = scanner.nextDouble(), triangleC = scanner.nextDouble();
if(triangleA + triangleB > triangleC && triangleB + triangleC > triangleA && triangleA + triangleC > triangleB){
Triangle triangle = new Triangle(triangleA, triangleB, triangleC);
triangle.printStats();
} else {
System.out.println("Invalid triangle sides.");
}
break;
default:
System.out.println("Invalid choice.");
}
scanner.close();
}
}
```
阅读全文