0
我想製作一個應用程序,將表達式從中綴模式轉換爲後綴和前綴模式。使用Java將中綴表達式轉換爲前綴和後綴表達式
例如:
綴:A + B * C
後綴:ABC * +
前綴:+ A * BC
我的兩個班想這樣,一類爲後綴轉換和其他類前綴轉換。
此外,我已經寫了堆一類是這樣的:
public class Stack {
int top = 0;
int stackSize = 0;
String[] stack;
public Stack(int stackSize){
this.stackSize = stackSize;
stack = new String[stackSize];
}
public int getTop(){
return top;
}
public void push(String arg)throws Exception{
if(top == stackSize){
throw new Exception("Stack is full!");
}
else{
this.stack[top++] = arg;
}
}
public String pop()throws Exception{
if(top == 0){
throw new Exception("Stack is empty");
}
else{
return this.stack[--top];
}
}
public int stackCount(){
return top++;
}
}
我想這個代碼後綴類:
public class Postfix {
Stack stack = new Stack(1000);
char []operators = {'(','*','%','/','+','-',')'};
char[] infixExpression;
public Postfix(String infixExpression){
this.infixExpression = infixExpression.toCharArray();
}
int priority(char operator){
int result = 0;
switch(operator){
case '(':
result = 1;
break;
case '*':
result = 2;
break;
case '%':
result = 3;
break;
case '/':
result = 4;
break;
case '+':
result = 5;
break;
case '-':
result = 5;
break;
case ')':
result = 7;
}
return result;
}
public String convertToPostfix(){
int priority;
String lastData;
String exp = "";
for(int i = 0;i<this.infixExpression.length;i++){
priority = priority(this.infixExpression[i]);
if(priority == 0){
exp += this.infixExpression[i];
}
else if(priority == 1){
try {
stack.push(String.valueOf(this.infixExpression[i]));
} catch (Exception e) {
e.printStackTrace();
}
}
else if(priority == 7){
while(stack.top != 0){
try {
lastData = stack.pop();
if(!lastData.equals("(")){
exp += lastData;
}
else{
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
else{
try {
if(stack.top != 0){
while(true){
lastData = stack.pop();
stack.push(lastData);
if(stack.top == 0 || lastData.equals("(") || priority(lastData.toCharArray()[0]) > priority){
stack.push(String.valueOf(this.infixExpression[i]));
break;
}
exp += stack.pop();
}
}else{
stack.push(String.valueOf(this.infixExpression[i]));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
if(stack.top != 0){
try {
while(stack.top != 0){
exp += stack.pop();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return exp;
}
}
但這並不與括號工作。
我想寫兩個類的後綴和前綴convert.its一個數學項目... 謝謝 –
仍然沒有問題。向我們展示您嘗試過的方式以及問題出在哪裏,我們可以爲您提供幫助。 – Blub
我不知道做這個項目 我試圖寫,但我有問題。 是否有必要在這裏寫我的代碼? –