java字尾表示式實現表示式求值
輸入一個表示式,如:2*3+(25-1)/6,請輸表示式的值,沒有小數,/號取整。
以下方法只適用簡單的加減乘除帶括號,並且沒有實現小數的問題!
import java.util.Scanner;
import java.util.Stack;
public class 表示式計算 {
private static Stack<String> num = new Stack<String>();//存字尾表示式
private static Stack<String> sign = new Stack<String>();//存入符號
private static Stack<Integer> result = new Stack<Integer>();//放結果
public static void getGroup(String line){//講字串轉換為字尾表示式
for(int i=0; i<line.length(); i++){
char c = line.charAt(i);
if((int)c>=48 && (int)c<=57){//當遇到數字的時候,判斷是不是多位數,然後在push進num
int j = i+1;
while(j<line.length() && (line.charAt(j)>=48 && line.charAt(j)<=57)){
j++;
}
num.push(line.substring(i, j));
i = j-1;
}else if(c == '('){//遇到左括號直接存進num
sign.push(String.valueOf(c));
}else if(c == ')'){//遇到右括號從sign中pop棧頂元素push到num知道遇到'(',然後再pop掉'('
while(!sign.peek().equals("(")){
num.push(sign.pop());
}
sign.pop();
}else{
int n = 0;
if(!sign.empty()){//如果sign中沒有元素,直接令n = 0
n = getNum(sign.peek().charAt(0));
}
int m = getNum(c);
if(m >= n){//如果當前元素的運算級別比棧頂元素運算級別要高,就直接push進sign
sign.push(String.valueOf(c));
}else{
while(m < n){//如果當前運算運算級別比sign棧頂元素運算級別要低,就將sign棧頂元素pop並且push進num,知道不符合條件
num.push(sign.pop());//輸入例子2*3+6/3的時候,這裡一直報錯
if(!sign.empty()){
n = getNum(sign.peek().charAt(0));
}else{
n = 0;
}
}
sign.push(String.valueOf(c));
}
}
}
while(!sign.empty()){
num.push(sign.pop());
}
}
private static int getNum(char c){
int n = 0;
switch(c){
case '+':
case '-':
n = 1;
break;
case '*':
case '/':
n = 2;
break;
}
return n;
}
private static void getResult(){//講得到的字尾表示式反轉遍歷,遇到數字就加入result,遇到符號就從result中取出兩個數進行運算然後將結果加入result
Stack<String> t = new Stack<String>();
while(!num.empty()){
t.push(num.pop());
}
String str = t.pop();
while(str != null){
if(str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/")){
int n = result.pop();
int m = result.pop();
int num = 0;
if(str.equals("+")) num = m+n;
if(str.equals("-")) num = m-n;
if(str.equals("*")) num = m*n;
if(str.equals("/")) num = m/n;
result.push(num);
}else{
result.push(Integer.parseInt(str));
}
if(!t.empty()){
str = t.pop();
}else{
str = null;
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
getGroup(line);
getResult();
System.out.println(result.peek());
//System.out.println(num);
//char[] exp = getGroup(line);//講字串轉換為字尾表示式
}
}