用java写一个简单的计算器
时间: 2023-11-21 07:05:17 浏览: 50
用java写一个简单计算器
5星 · 资源好评率100%
好的,下面是一个简单的 Java 计算器示例代码:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个数字:");
double num1 = scanner.nextDouble();
System.out.print("请输入第二个数字:");
double num2 = scanner.nextDouble();
System.out.print("请选择运算符(+、-、*、/):");
String operator = scanner.next();
double result = 0.0;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0) {
System.out.println("除数不能为零!");
return;
}
result = num1 / num2;
break;
default:
System.out.println("输入的运算符不正确!");
return;
}
System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
}
}
```
运行程序后,按照提示输入两个数字和运算符,程序将输出计算结果。
阅读全文