我正在尝试编写一个程序来评估用户输入的表达式。我知道我需要有单独的方法,所以它首先评估乘法和除法,然后再添加加法和减法。这是我到目前为止得到的。当我尝试任何涉及乘法或除法的事情时,比如 6*6,它只会打印第一个字符,在这种情况下它只是“6”。有任何想法吗?
import java.util.Scanner;
class Expressions {
String e;
void setExpressions(String exp) {
e = exp;
}
String evaluate() {
String n = "";
for (int i = 0; i < e.length(); i++)
if (e.charAt(i) == '*' || e.charAt(i) == '/') {
n += e.charAt(i);
}
else if (e.charAt(i) == '+' || e.charAt(i) == '/') {
evaluateMD();
n = "";
}
else
n += e.charAt(i);
return n;
}
int evaluateMD () {
int r = 1;
int n = 0;
char op = '*';
for (int i = 0; i < evaluate().length(); i++)
if (evaluate().charAt(i) == '*' || evaluate().charAt(i) == '/') {
if (op == '*')
r *= n;
else
r /= n;
n = 0;
op = evaluate().charAt(i);
}
else if (evaluate().charAt(i) == '*' || evaluate().charAt(i) == '/')
n = 0;
else //digits
n = n*10 + (evaluate().charAt(i)-'0');
if (op == '+') //last operation
r *= n;
else
r /= n;
return r;
}
int evaluateAS() {
//e has +, - only, multiple digit numbers
int r = 0;
int n = 0;
char op = '+';
for (int i = 0; i < e.length(); i++)
if (e.charAt(i) == '+' || e.charAt(i) == '-') {
if (op == '+')
r += n;
else
r -= n;
n = 0;
op = e.charAt(i);
}
else if (e.charAt(i) == '*' || e.charAt(i) == '/')
n = 0;
else //digits
n = n*10 + (e.charAt(i)-'0');
if (op == '+') //last operation
r += n;
else
r -= n;
return r;
}
}
public class hw10 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
Expressions myE = new Expressions();
System.out.print("Enter E:");//E for expression
String e = in.next();
myE.setExpressions(e);
//int r = myE.evaluate1();
int r = myE.evaluateAS();
System.out.println(e+" = "+r);
}
}