双栈算术表达式求值算法

来源:互联网 发布:淘宝怎么异地发货 编辑:程序博客网 时间:2024/05/11 01:28
package Basic;import java.util.Scanner;import java.util.Stack;public class Evaluate {public static void main(String[] args) {Stack<Character> op = new Stack<Character>();Stack<Double> val = new Stack<Double>();System.out.println("input the string to be evaluated:");Scanner scanner = new Scanner(System.in);//String s = scanner.next(); //对输入的每一个字符串进行处理。要想按照行的所有字符串处理 用nexLine()//while(s != null){// System.out.println(s);// s = scanner.next();//}String s = scanner.nextLine();int i = 0;while(i < s.length()){  //switch语句表达式只能使用Java八种原始类型(char,byte,short,int,long,double,float)char c = s.charAt(i);if(Character.isDigit(c)){val.push((double) Character.digit(c, 10));}else{switch(c){                      //不能使用字符串case '(': break;case '+': op.push(c);break;case '-': op.push(c);break;case '*': op.push(c);break;case '/': op.push(c);break;case ')': {char ch = op.pop();        double v = val.pop();        switch(ch){        case '+': v = v + val.pop();break;        case '-': v = v - val.pop();break;        case '*': v = v * val.pop();break;        case '/': v = val.pop() / v;break;        }        val.push(v);        System.out.println("now val's peek is:"+val.peek());};break;}}i++;}System.out.println("the result is:"+val.pop());}}

0 0
原创粉丝点击