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

方法的输入参数是一个字符串(内容是一个表达式,有多个加减运算),方法输出的是一个整型结果。
只能是一个函数
public int A(String ex){
int result=0;
.........
return result;
}
请问怎么把之这个函数补充完整

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

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);
}
}

运行结果:

温馨提示:内容为网友见解,仅供参考
第1个回答  2018-10-18
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

追问

大神能写一下栈的吗?万分感谢,要分的话,可以给您多加点

追答

你把那个https的链接复制到浏览器里面,进去看一下,那个就是栈的一个实现。

第2个回答  2018-10-18
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<expArr.length; 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("表达式不合法");
}
}

第3个回答  2018-10-18
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;
}
第4个回答  2018-10-18
你说的操作叫做EVAL,搜索java eval就可以找到大把的内容。追问

大哥,我需要通过函数实现,我的想法是通过栈,但是忘了怎么做了。你说的eval 我没用过。我要的就是把上面的函数补充完整,谢谢

追答

已经说过了

追问

大神能帮帮忙把上面的函数补充完成,让我学习一下吗,万分感谢

相似回答