双栈算术表达式求值算法

package Basic;

import java.util.Scanner;
import java.util.Stack;

public class Evaluate {
public static void main(String[] args) {
	Stack op = new Stack();
	Stack val = new Stack();
	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());
}
}

你可能感兴趣的:(学习笔记)