写一个基于Java的四则运算
时间: 2024-05-16 19:12:51 浏览: 44
以下是一个简单的基于Java的四则运算实现:
```java
import java.util.Scanner;
public class ArithmeticCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double num1, num2, result;
String operator;
System.out.println("请输入第一个操作数:");
num1 = scanner.nextDouble();
System.out.println("请输入第二个操作数:");
num2 = scanner.nextDouble();
System.out.println("请输入运算符(+、-、*、/):");
operator = scanner.next();
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 "/":
if(num2 == 0) {
System.out.println("除数不能为0!");
} else {
result = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + result);
}
break;
default:
System.out.println("无效的运算符!");
}
}
}
```
此代码将提示用户输入两个操作数和运算符,然后根据运算符执行相应的计算并输出结果。注意,此代码未处理输入错误或异常情况。
阅读全文