java计算器正负数
时间: 2024-06-23 13:01:32 浏览: 9
Java中的计算器设计通常会涉及到基本的数学运算,包括加减乘除以及处理正负数。以下是一个简单的Java类,用于实现基础的四则运算,包括正负数:
```java
public class SimpleCalculator {
// 加法
public static double add(double num1, double num2) {
return num1 + num2;
}
// 减法
public static double subtract(double num1, double num2) {
return num1 - num2;
}
// 乘法
public static double multiply(double num1, double num2) {
return num1 * num2;
}
// 除法
public static double divide(double num1, double num2) {
if (num2 != 0) {
return num1 / num2;
} else {
throw new IllegalArgumentException("Division by zero is not allowed.");
}
}
// 用户输入并计算
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.println("Enter second number: ");
double num2 = scanner.nextDouble();
System.out.println("Enter an operator (+, -, *, /): ");
String operator = scanner.next();
switch (operator) {
case "+":
System.out.printf("Result: %.2f\n", add(num1, num2));
break;
case "-":
System.out.printf("Result: %.2f\n", subtract(num1, num2));
break;
case "*":
System.out.printf("Result: %.2f\n", multiply(num1, num2));
break;
case "/":
try {
System.out.printf("Result: %.2f\n", divide(num1, num2));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
break;
default:
System.out.println("Invalid operator. Please use +, -, *, or /.");
break;
}
scanner.close();
}
}
```
在这个例子中,用户可以输入两个数字和一个运算符,然后程序会根据运算符执行相应的操作。注意,对于除法,我们检查了除数是否为零以避免运行时错误。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)