输入一个表达式,如: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);//讲字符串转换为后缀表达式
}
}