java中用switch编写简单计算器: ---=菜单==== 1-------加法2-----减法3-------乘法4-------除法 === 请输入你的选择:1 请输入要运算的数据:12 运算结果: 1.0+2.0=3.0
时间: 2024-03-19 20:38:27 浏览: 74
在Java中,可以使用switch语句编写一个简单的计算器。以下是一个示例代码:
```java
import java.util.Scanner;
public class Calculator {
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--除法");
System.out.println("===");
System.out.print("请输入你的选择:");
int choice = scanner.nextInt();
System.out.print("请输入要运算的数据:");
double num1 = scanner.nextDouble();
double num2 = scanner.nextDouble();
double result = 0.0;
switch (choice) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
result = num1 / num2;
break;
default:
System.out.println("无效的选择");
return;
}
System.out.println("运算结果:");
System.out.println(num1 + "+" + num2 + "=" + result);
}
}
```
运行以上代码,根据菜单选择相应的操作,输入要运算的数据,即可得到运算结果。
阅读全文
相关推荐


















