我试图简化这个 if 语句以避免代码重复和 if 语句。我还希望能够传递超过 2 个参数。即5+10*2/2。有任何想法吗?
public static double randomExpressionDraft(String exp) {
double primeResult = 0;
double newResult = 0;
for (int i = 0; i < exp.length(); i++) {
if (exp.charAt(i) == '*') {
newResult = Integer.parseInt(exp.substring(0, i)) * Integer.parseInt(exp.substring(i + 1, exp.length()));
primeResult = newResult;
System.out.println(primeResult);
} else if (exp.charAt(i) == '/') {
newResult = Integer.parseInt(exp.substring(0, i)) / Integer.parseInt(exp.substring(i + 1, exp.length()));
primeResult = newResult;
System.out.println(primeResult);
} else if (exp.charAt(i) == '+') {
newResult = Integer.parseInt(exp.substring(0, i)) + Integer.parseInt(exp.substring(i + 1, exp.length()));
primeResult = newResult;
System.out.println(primeResult);
} else if (exp.charAt(i) == '-') {
newResult = Integer.parseInt(exp.substring(0, i)) - Integer.parseInt(exp.substring(i + 1, exp.length()));
primeResult = newResult;
System.out.println(primeResult);
}
}
return primeResult;
}