【高分悬赏】Java实现一个方法计算一个只有加减法运算的表达式的值

2025-03-06 17:47:19
推荐回答(5个)
回答1:

这个问题很简单,只有加减运算,没有运算优先级,不需要用到堆栈就可以。下面是代码:

public class App {

public static int A(String ex) throws Exception {

int result = 0;

String str = "";

for (int i = 0; i < ex.length(); i++) {

char ch = ex.charAt(i);

if (ch >= '0' && ch <= '9') {

str += ch;

} else if (ch == '+' || ch == '-') {

result += Integer.parseInt(str);
str = "" + ch;

} else if (ch == ' ') {
continue;
}else {
throw new Exception("无效的表达式。");
}
}

if (str != "") {
result += Integer.parseInt(str);
}

return result;
}

public static void main(String[] args) throws Exception {

int result = A("1 - 2 + 3 + 4 - 23");

System.out.println("result=" + result);
}
}

运行结果:

回答2:

private static ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");

    public static void main(String[] args) throws ScriptException {
        String ex = "2 + 3 + 4";
        int result = A(ex);
        System.out.println(result);
    }

    public static int A(String ex) throws ScriptException {
        int result = (int) engine.eval(ex);
        return result;
    }
    
    
    
上面是一种简单的方法实现,如果要自己通过栈实现,可以能考下面的代码:

https://www.cnblogs.com/gmq/archive/2013/05/30/3108849.html

回答3:

public static int getResult(String exp) throws Exception{
int result = 0;
String str = exp.trim().replaceAll("\\-", "\\+\\-");
String[] expArr = str.split("\\+");
for(int i=0; i if(!expArr[i].equals("")){
result = result+Integer.valueOf(expArr[i]);
}
}
return result;
}
public static void main(String[] args) {
String exp = "-3+0-22+8-9 ";
try {
int result = getResult(exp);
System.out.println(result);
} catch (Exception e) {
//e.printStackTrace();
System.out.println("表达式不合法");
}
}

回答4:

public static void main(String[] args) {
// TODO Auto-generated method stub
Main main = new Main();
int reslut = main.A("1+2+5-1");
System.out.println(reslut);
}
public int A(String ex) {
int result = 0;
String[] strs = ex.split("\\+");
for (int i = 0; i < strs.length; i++) {
String[] str = strs[i].split("\\-");
for (int j = 0; j < str.length; j++) {
result += Integer.parseInt(str[j]);
}
}
return result;
}

回答5:

你说的操作叫做EVAL,搜索java eval就可以找到大把的内容。