表达式运算

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38158541/article/details/79245822

import java.util.Scanner;

import java.util.Stack;


public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
Stack<Integer> nums = new Stack<Integer>();
Stack<Character> opes = new Stack<Character>();
char ch[] = s.toCharArray();
int n = 0;               //保存每一个数字
for(int i = 0; i < s.length(); i++){
if(Character.isDigit(ch[i])){
n = n * 10 + Integer.parseInt(String.valueOf(ch[i]));
}else{
//如果是数字压入
if(n != 0){
nums.push(n);
n = 0;
}
//如果是操作符,进行判断
if(isType(ch[i]) > 0){
if(opes.isEmpty()){             //如果运算符栈为空,直接压入
opes.push(ch[i]);
}else{
if(isType(ch[i]) <= isType(opes.peek())){  
//如果优先级小于栈顶的,要先弹出栈顶运算符,与数字栈中两个栈顶数字进行运算,
//运算结果入数字栈后,然后再将该运算符入栈
int t = cal(nums.pop(), nums.pop(), opes.pop());
nums.push(t);
}
opes.push(ch[i]);
}
}
//如果遇到“(”,先将其压入栈,然后直到遇到“)”,将栈中元素输出,知道遇到“(”
if(ch[i] == '('){
opes.push(ch[i]);
}else if(ch[i] == ')'){
while(opes.peek() != '('){
int t = cal(nums.pop(), nums.pop(), opes.pop());
nums.push(t);
}
opes.pop();               //将“(”移除
}
}
}
//此时判断运算符栈中是否还有操作符,如果有,将他们一次输出并运算
while(!opes.isEmpty()){
int t = cal(nums.pop(), nums.pop(), opes.pop());
nums.push(t);
}
System.out.println(nums.pop());
scanner.close();
}
//进行运算,但是要注意栈是先进后出,所以传下来的对应的是num1是栈顶,num2是次,所以运算是num2和num1的顺序
private static int cal(int num1, int num2, char c) {
// TODO Auto-generated method stub
int result = 0;
if(c == '+'){
result = num2 + num1;
}
if(c == '-'){
result = num2 - num1;
}
if(c == '*'){
result = num2 * num1;
}
if(c == '/'){
result = num2 / num1;
}
return result;
}
//设置运算符的优先级
private static int isType(char c) {
// TODO Auto-generated method stub
if(c == '+' || c == '-'){
return 1;
}
if(c == '*' || c == '/'){
return 2;
}
return 0;
}
}

猜你喜欢

转载自blog.csdn.net/weixin_38158541/article/details/79245822