这个问题很简单,只有加减运算,没有运算优先级,不需要用到堆栈就可以。下面是代码:
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);
}
}
运行结果:
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
public static int getResult(String exp) throws Exception{
int result = 0;
String str = exp.trim().replaceAll("\\-", "\\+\\-");
String[] expArr = str.split("\\+");
for(int i=0; iif(!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("表达式不合法");
}
}
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;
}
你说的操作叫做EVAL,搜索java eval就可以找到大把的内容。