我需要修改此代码以使用操作顺序并能够进行乘法和除法,但我不知道从哪里开始。我知道是否适用于加法和减法,但我只需要弄清楚如何使其乘法和除法。
import java.util.Scanner;
class Expressions {
String e;
void setExpressions(String exp){
e =exp;
}
int evaluate1(){
//e has +. -. only, single digit numbers
int r = e.charAt(0)-'0';
int l = e.length();
for(int i=1; i<=l-1; i++ )
if (e.charAt(i) == '+')
r += (e.charAt(i+1)-48);
else
r -= (e.charAt(i+1)-'0');
return r;
}
int evaluateAS(){
//e has +, -, only, multiple digit numbers
int r = 0;
int n = 0;
int 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 //digits
n = n*10+(e.charAt(i) - '0');
}
if (op == '+')
r += n;
else
r -= n;
return r;
}
}
public class Runner {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Expressions myE = new Expressions();
System.out.println("Enter E: ");
String e = in.next();
myE.setExpressions(e);
//int r = myE.evaluate1();
int r = myE.evaluateAS();
System.out.println(e+" = "+ r);
}
}