用Java写一个会加减乘除的计算器
时间: 2023-10-04 07:07:12 浏览: 137
好的,下面是一个简单的 Java 计算器程序,可以进行加减乘除四则运算:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入第一个数字:");
double num1 = scanner.nextDouble();
System.out.println("请输入运算符(+、-、*、/):");
String operator = scanner.next();
System.out.println("请输入第二个数字:");
double num2 = scanner.nextDouble();
double result = 0;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
default:
System.out.println("错误的运算符!");
break;
}
System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
}
}
```
运行程序后,按照提示输入两个数字和运算符,程序将会输出运算结果。注意,在除法运算中,如果除数为 0,程序会抛出异常。
阅读全文