用Java实现计算器的功能
时间: 2024-04-10 15:27:54 浏览: 22
可以使用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 operand1 = scanner.nextDouble();
System.out.print("请输入运算符(+, -, *, /): ");
String operator = scanner.next();
System.out.print("请输入第二个操作数: ");
double operand2 = scanner.nextDouble();
double result = 0;
switch (operator) {
case "+":
result = operand1 + operand2;
break;
case "-":
result = operand1 - operand2;
break;
case "*":
result = operand1 * operand2;
break;
case "/":
if (operand2 != 0) {
result = operand1 / operand2;
} else {
System.out.println("错误:除数不能为零!");
System.exit(0);
}
break;
default:
System.out.println("错误:无效的运算符!");
System.exit(0);
}
System.out.println("结果: " + result);
}
}
```
这个示例中,我们使用 `Scanner` 类来接收用户输入。首先,我们要求用户输入第一个操作数、运算符和第二个操作数。然后,根据运算符进行相应的计算,并将结果输出。
请注意,这只是一个简单的示例,可能没有考虑到所有的边界情况和错误处理。你可以根据需要进行扩展和改进。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)