我有一个表达式评估程序,但问题是它没有识别出-12 / -4的否定,我的IDE认为它除以零。我测试了我已经拥有的类似代码,似乎它以某种方式将12改为0,我不知道在哪里。任何人都可以提供的帮助将非常感激!
import java.util.Scanner;
class Expressions {
String e;
void setExpressions(String ee) {
e = ee;
}
String getE() {
return e;
}
//evaluate arithemetic expressions e
//assuming e has only *, /, and operands.
//12*345/3/72*890
int evalMD(String e) {
int r = 1, 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 //digits
n = 10*n+(e.charAt(i)-'0');
if (op == '*') //last number
r *= n;
else
r /= n;
return r;
}
//evaluate arithemetic expressions e
//assuming e has +, -, *, /, and operands.
//12*3-34/5*56+3-72
int evalE() {
int r = 0;
String n = "";
char op = '+';
for (int i = 0; i < e.length(); i++)
if (e.charAt(i) == '+' || e.charAt(i) == '-') {
if (op == '+')
r += evalMD(n);
else
r -= evalMD(n);
n = "";
op = e.charAt(i);
}
else //digits
n += e.charAt(i);
if (op == '+') //last number
r += evalMD(n);
else
r -= evalMD(n);
return r;
}
}
public class Lab13 {
public static void main(String[] args) {
Expressions myE = new Expressions();
Scanner in = new Scanner(System.in);
System.out.print("Enter expression(Type q to stop): ");
String e = in.nextLine();
while (e.charAt(0) != 'q' && e.charAt(0) != 'Q') {
myE.setExpressions(e);
System.out.println(myE.evalE());
System.out.print("Enter expression(Type q to stop): ");
e = in.nextLine();
}
System.out.println("Thank you for using my program!!!");
}
}