用java 编写一个程序,用于计算 x op y 这样的表达式的值,表达式从命令行输人,其中o为十,一,*,/,% 几种运算符之一。
时间: 2024-05-01 12:22:19 浏览: 141
以下是用Java编写的程序,可以计算命令行输入的表达式的值:
```java
public class Calculator {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("Usage: java Calculator x op y");
return;
}
double x = Double.parseDouble(args[0]);
String op = args[1];
double y = Double.parseDouble(args[2]);
double result = 0.0;
switch (op) {
case "+":
result = x + y;
break;
case "-":
result = x - y;
break;
case "*":
result = x * y;
break;
case "/":
result = x / y;
break;
case "%":
result = x % y;
break;
default:
System.out.println("Invalid operator: " + op);
return;
}
System.out.println(x + " " + op + " " + y + " = " + result);
}
}
```
运行示例:
```
java Calculator 2.5 + 3.7
2.5 + 3.7 = 6.2
java Calculator 4.0 - 1.5
4.0 - 1.5 = 2.5
java Calculator 5.0 \* 2.0
5.0 * 2.0 = 10.0
java Calculator 6.0 / 3.0
6.0 / 3.0 = 2.0
java Calculator 7.0 % 3.0
7.0 % 3.0 = 1.0
java Calculator 8.0 # 2.0
Invalid operator: #
```
阅读全文