import java.lang.*; public class InToPost{ // ----- 変数の宣言 ----- private StackX theStack; private String input; private String output = ""; // ----- コンストラクタ ----- public InToPost(String in){ this.input = in; int stackSize = this.input.length(); this.theStack = new StackX(stackSize); } // ----- 後置式への翻訳 ----- public String doTrans(){ for(int i = 0; i < this.input.length(); i++){ char ch = this.input.charAt(i); this.theStack.displayStack("For " + ch + " "); switch(ch){ case '+': case '-': gotOper(ch, 1); break; case '*': case '/': gotOper(ch, 2); break; case '(': this.theStack.push(ch); break; case ')': this.gotParen(ch); break; default: this.output = this.output + ch; break; } } while(!this.theStack.isEmpty()){ this.theStack.displayStack("While "); this.output = this.output + this.theStack.pop(); } this.theStack.displayStack("End "); return this.output; } // ----- 入力から演算子を取得する ----- public void gotOper(char opThis, int prec1){ while(!this.theStack.isEmpty()){ char opTop = this.theStack.pop(); if(opTop == '('){ this.theStack.push(opTop); break; } else{ int prec2; if(opTop == '+' || opTop == '-'){ prec2 = 1; } else{ prec2 = 2; } if(prec2 < prec1){ this.theStack.push(opTop); break; } else{ this.output = this.output + opTop; } } } this.theStack.push(opThis); } // ----- 入力から閉じ括弧をもらった ----- public void gotParen(char ch){ while(!this.theStack.isEmpty()){ char chx = this.theStack.pop(); if(chx == '('){ break; } else{ this.output = this.output + chx; } } } }