java实现计算器计算代码
时间: 2023-09-06 19:07:18 浏览: 86
以下是一个简单的 Java 计算器示例程序:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double num1, num2, result;
char operator;
System.out.print("请输入第一个数字: ");
num1 = scanner.nextDouble();
System.out.print("请输入运算符 (+, -, *, /): ");
operator = scanner.next().charAt(0);
System.out.print("请输入第二个数字: ");
num2 = scanner.nextDouble();
switch (operator) {
case '+':
result = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + result);
break;
case '-':
result = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + result);
break;
case '*':
result = num1 * num2;
System.out.println(num1 + " * " + num2 + " = " + result);
break;
case '/':
result = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + result);
break;
default:
System.out.println("无效的运算符!");
break;
}
}
}
```
该程序会提示用户输入两个数字和一个运算符,然后计算并输出结果。注意,此程序没有处理除数为零的情况。
阅读全文