java计算不同图形面积代码
时间: 2023-06-27 07:03:09 浏览: 143
以下是Java计算不同图形面积的示例代码:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请选择要计算面积的图形:");
System.out.println("1. 正方形");
System.out.println("2. 长方形");
System.out.println("3. 圆形");
System.out.println("4. 三角形");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("请输入正方形的边长:");
double squareSide = scanner.nextDouble();
double squareArea = squareSide * squareSide;
System.out.println("正方形的面积为:" + squareArea);
break;
case 2:
System.out.println("请输入长方形的长度:");
double rectangleLength = scanner.nextDouble();
System.out.println("请输入长方形的宽度:");
double rectangleWidth = scanner.nextDouble();
double rectangleArea = rectangleLength * rectangleWidth;
System.out.println("长方形的面积为:" + rectangleArea);
break;
case 3:
System.out.println("请输入圆形的半径:");
double radius = scanner.nextDouble();
double circleArea = Math.PI * radius * radius;
System.out.println("圆形的面积为:" + circleArea);
break;
case 4:
System.out.println("请输入三角形的底边长度:");
double base = scanner.nextDouble();
System.out.println("请输入三角形的高:");
double height = scanner.nextDouble();
double triangleArea = 0.5 * base * height;
System.out.println("三角形的面积为:" + triangleArea);
break;
default:
System.out.println("无效选择!");
}
scanner.close();
}
}
```
该程序会通过键盘输入让用户选择要计算面积的图形类型,然后根据用户的选择分别计算不同图形的面积并输出结果。
阅读全文