Java怎么实现输入一个string表达式然后输出计算的结果

2024-12-04 17:47:53
推荐回答(1个)
回答1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//算式
public static void test32() throws Exception{
System.out.println("请输入算式:");
Scanner scanner = new Scanner(System.in);
String str = scanner.next("-?\\d*\\.?\\d+[+-/*]-?\\d*\\.?\\d+");
String[] xyStr = str.split("[+-/*]");
float x = Float.parseFloat(xyStr[0]);
float y = Float.parseFloat(xyStr[1]);
float r = 0;
char opt = '+';
if(str.contains("+")){
opt = '+';
r = x + y;
}else if(str.contains("-")){
opt = '-';
r = x - y;
}else if(str.contains("*")){
opt = '*';
r = x * y;
}else if(str.contains("/")){
opt = '/';
r = x / y;
}
System.out.println(x+""+opt+y+"="+r);
}