java实现计算器程序
时间: 2023-06-13 15:08:02 浏览: 83
以下是一个简单的Java计算器程序实现示例:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
double num1, num2, result;
char operator;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
operator = scanner.next().charAt(0);
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
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("Invalid operator.");
return;
}
System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
}
}
```
运行程序后,用户输入第一个数字、操作符和第二个数字,程序根据操作符计算并输出结果。注意,此程序还没有实现输入验证和异常处理,您可以根据需要进行改进。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)