package Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class tomcat{
public static void main(String[] args) {
//1, 2, 3, +, 4, *, +, 5, -
String exclp="1+((2+3)*4)-5";
List<String> list=getcode(exclp);//第一步处理
System.out.println(list);
System.out.println(calc(getlastcode(list)));
}
/**
*
*
* @param data 传需要处理的字符串 多位数
* @return 处理的中缀表达式子
*/
public static List<String> getcode(String data){
List<String> list=new ArrayList();
String yuan="",ok="";
for (int i = 0; i < data.length(); i++) {
yuan=data.substring(i,i+1);
switch (yuan) {
case "+":
case "-":
case "*":
case "/":
case "(":
case ")":
if(!ok.equals(""))
list.add(ok);
list.add(yuan);
ok="";
break;
default:
ok+=yuan;
break;
}
}
list.add(ok);
return list;
}
/**
*
* @param 传中缀表达
* @return 后缀表达
*/
public static List<String> getlastcode(List<String> list) {
Stack<String> stack=new Stack();
List<String> listtwo=new ArrayList(list.size());
for (String string : list) {//遍历我的值
if(string.matches("\\d+")) {// 数字入栈
listtwo.add(string);
}else if(string.equals("(")) {
stack.push(string);
}else if(string.equals(")")) {
while(!stack.peek().equals("("))
listtwo.add(stack.pop());
stack.pop();
}else {
while(stack.size()!=0&&queue(stack.peek())>=queue(string)) {
listtwo.add(stack.pop());
}
stack.push(string);
}
}
while(!stack.isEmpty()) {
listtwo.add(stack.pop());
}
return listtwo;
}
public static int queue(String code) {//优先级
return code.matches("[+-/*/]")? code.matches("[+-]")? 1:2: 0;
}
//传后缀计算值
public static int calc(List<String> list) {
Stack<String> stack=new Stack();
for (String string : list) {
if(string.matches("\\d+")) {//数字直接压
stack.push(string);
}else {//计算
stack.push(calc(Integer.parseInt(stack.pop()),Integer.parseInt(stack.pop()),string)+"");
}
}
return Integer.parseInt(stack.pop());
}
public static int calc(int a,int b,String code) {
return code.equals("+")||code.equals("-")? code.equals("+") ? a+b: b-a : code.equals("*") ? a*b:b/a;
}
}
JAVA实现计算机功能逆波兰
最新推荐文章于 2022-12-15 12:32:04 发布