您的位置:首页 > 其它

表达式计算

2018-03-30 21:54 162 查看
import java.util.Scanner;
import java.util.Stack;
import java.util.LinkedList;

public class Main{
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
while(scanner.hasNext()) {
String string=scanner.nextLine();

//将中缀表达式转化为后缀表达式
LinkedList<Object> link=new LinkedList<Object>();//后缀表达式
Stack<Character> opstack=new Stack<Character>();//操作符栈
int x=0;
boolean isInt=false;
for(int i=0;i<string.length();i++) {
char ch=string.charAt(i);
if(ch>='0' && ch<='9') {
x=x*10+ch-'0';
isInt=true;
}
else {
if(isInt)
link.add((Integer)x);
x=0;
isInt=false;
if(ch=='(') {
opstack.push(ch);
}
else if(ch==')') {
while(opstack.peek()!='(') {
link.add(opstack.pop());
}
opstack.pop();
}
else {
while(!opstack.empty() && priority(opstack.peek())>=priority(ch))
link.add(opstack.pop());
opstack.push(ch);
}
}
}
if(x!=0)
link.add(x);
while(!opstack.empty())
link.add(opstack.pop());

//计算后缀表达式的值
Stack<Integer> integers=new Stack<Integer>();
for(Object every:link) {
if(every instanceof Integer) {
integers.push((Integer)every);
}
else {
int b=integers.pop();
int a=integers.pop();
char op=(Character)every;
if(op=='+')
integers.push(a+b);
else if(op=='-')
integers.push(a-b);
else if(op=='*')
integers.push(a*b);
else
integers.push(a/b);
}
}
System.out.println(integers.peek());
}
scanner.close();
}

//求运算符的优先级,不考虑数字和()
public static int priority(char op) {
switch(op) {
case '*':
case '/':return 2;
case '+':
case '-':return 1;
default:return 0;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: