import java.util.Scanner;
import java.util.Stack;
public class 逆波兰表达式 {
public static void main(String[] args) {
System.out.println("请输入算式:");
Scanner in = new Scanner(System.in);
String line = in.nextLine();
System.out.println(line+"****");
if(line != null && !line.isEmpty()) {
int res = resolve(line.trim());
System.out.println(String.valueOf(res));
}
}
//该解法为算法(第四版)的方法,建立两个栈,一个存操作符,一个存数,挺好理解的
public static int resolve(String expr) {
Stack<String> ops = new Stack<String>();
Stack<Integer> vals = new Stack<Integer>();
char[] newstr = expr.toCharArray();
for(int i=0;i<newstr.length;i++){
String s= String.valueOf(newstr[i]);
if(s.equals("("));
else if(s.equals("+")) ops.push(s);
else if(s.equals("-")) ops.push(s);
else if(s.equals("*")) ops.push(s);
else if(s.equals("/")) ops.push(s);
else if(s.equals("sqrt")) ops.push(s);
else if(s.equals(")"))
{
String op = ops.pop();
int v=vals.pop();
if(op.equals("+")) v=vals.pop()+v;
else if(op.equals("-")) v=vals.pop()-v;
else if(op.equals("*")) v=vals.pop()*v;
else if(op.equals("/")) v=vals.pop()/v;
else if(op.equals("sqrt")) v=(int)Math.sqrt(v);
vals.push(v);
}
else vals.push(Integer.parseInt(s));
}
return vals.pop();
}
}
import java.util.Stack;
public class 逆波兰表达式 {
public static void main(String[] args) {
System.out.println("请输入算式:");
Scanner in = new Scanner(System.in);
String line = in.nextLine();
System.out.println(line+"****");
if(line != null && !line.isEmpty()) {
int res = resolve(line.trim());
System.out.println(String.valueOf(res));
}
}
//该解法为算法(第四版)的方法,建立两个栈,一个存操作符,一个存数,挺好理解的
public static int resolve(String expr) {
Stack<String> ops = new Stack<String>();
Stack<Integer> vals = new Stack<Integer>();
char[] newstr = expr.toCharArray();
for(int i=0;i<newstr.length;i++){
String s= String.valueOf(newstr[i]);
if(s.equals("("));
else if(s.equals("+")) ops.push(s);
else if(s.equals("-")) ops.push(s);
else if(s.equals("*")) ops.push(s);
else if(s.equals("/")) ops.push(s);
else if(s.equals("sqrt")) ops.push(s);
else if(s.equals(")"))
{
String op = ops.pop();
int v=vals.pop();
if(op.equals("+")) v=vals.pop()+v;
else if(op.equals("-")) v=vals.pop()-v;
else if(op.equals("*")) v=vals.pop()*v;
else if(op.equals("/")) v=vals.pop()/v;
else if(op.equals("sqrt")) v=(int)Math.sqrt(v);
vals.push(v);
}
else vals.push(Integer.parseInt(s));
}
return vals.pop();
}
}