Java实现栈来做一个将中缀表达式转化为后缀表达式的程序,中缀表达式更符合我们的主观感受,后缀表达式更适合计算机的运算,下面直接上代码吧:
package Character1;
import java.util.Stack;
public class Calculter {
private static Stack<Object> shu = new Stack<Object>();
private static Stack<Object> fu = new Stack<Object>();
static String oldString = "(1+2)+2*(4-1)+6/3";
public static void main(String[] args) {
char[] chars = new char[oldString.length()];
for (int i = 0; i < oldString.length(); i++) {
chars[i] = oldString.charAt(i);
}
for (int i = 0; i < chars.length; i++) {
if (isCaoZuoFu(chars[i])) {
if (chars[i] == '(') {
fu.add(chars[i]);
}
if (chars[i] == ')') {
// System.out.println(fu);
while ((char) fu.peek() != '(') {
shu.add(fu.pop());
}
if ((char) fu.peek() == '(') {
fu.pop();
}
// System.out.println(fu+"-----");
while (fu.isEmpty() != true) {
char temp = (char) fu.pop();
fu.add(temp);
if (temp == '*' || temp == '/') {
shu.add(temp);
fu.pop();
} else {
break;
}
}
} else if (chars[i] == '*') {
fu.add(chars[i]);
} else if (chars[i] == '/') {
fu.add(chars[i]);
} else if (chars[i] == '+') {
fu.add(chars[i]);
} else if (chars[i] == '-') {
fu.add(chars[i]);
}
} else {
shu.add(chars[i]);
}
}
// System.out.println(fu.toString());
// System.out.println(shu.toString());
System.out.println("原字符串是:"+oldString);
System.out.println("------------------以上部分千万不要改动了");
while(fu.isEmpty()!=true){
shu.add(fu.pop());
}
System.out.println("操作符栈:"+fu.toString());
System.out.println("操作数栈:"+shu.toString());
System.out.println("----------------------中缀表达式转换为后缀表达式的结果!");
int result=JiSuan(Reverse(shu));
System.out.println("表达式最终答案:"+result);
}
public static int JiSuan(Stack<Object> stack){
int result=0;
Stack<Object>temp=new Stack<Object>();//存放后缀表达式的操作数的栈
while(stack.isEmpty()!=true){
if(!isCaoZuoFu((char)stack.peek())){
temp.add(stack.pop());
System.out.println(temp);
}else{
int o1=Integer.parseInt(temp.pop().toString());
int o2=Integer.parseInt(temp.pop().toString());
if(stack.isEmpty()!=true){
if((char)stack.peek()=='+'){
temp.add(o2+o1);
}
if((char)stack.peek()=='-'){
temp.add(o2-o1);
}
if((char)stack.peek()=='*'){
temp.add(o2*o1);
}
if((char)stack.peek()=='/'){
temp.add(o2/o1);
}
stack.pop();
}
}
}
return (int) temp.peek();
}
public static Stack<Object> Reverse(Stack<Object> shu){
Stack<Object> reverseStack=new Stack<Object>();
while(shu.isEmpty()!=true){
reverseStack.add(shu.pop());
}
System.out.println("来个反序:"+reverseStack);
return reverseStack;
}
//此方法用于判断对应字符是不是操作符,其中case的数字是对应的ASCII码。
public static boolean isCaoZuoFu(char b) {
int temp = (char) b;
switch (temp) {
case 43:
case 45:
case 42:
case 47:
case 40:
case 41:
return true;
default:
return false;
}
}
}
下面就是程序的运行结果:
由于时间匆忙,未来得及做注释,导致此程序可读性较差,还望读者取精华弃糟粕。也希望对我的书写中有错误的地方予以指正,旨在我们的共同进步!