2015-12-09 2 views
0

Хорошо, поэтому при запуске программы ошибок нет, но ожидаемый результат не возвращается. Программа просто перепечатывает строку вместо ее преобразования. Здесь приведен код для класса PostfixtoInfix2. Метод полагается на другие методы, которые работают правильно. Я не могу определить, какой метод работает некорректно. Любые идеи, лучшие соглашения о кодировании или решения приветствуются.Мой класс класса драйвера, но не возвращает ожидаемое значение

import java.util.Stack; 
public class PostfixtoInfix2 
    /* 
* This class takes an expression in Infix and translates it to Prefix. 
* */ 

{ 
    public String expression; 
    public Stack <Character> s= new Stack(); 


    public String PostfixtoInfix(String e) 
    {expression = e; 
    String output =""; 
    for(int i=0; i < expression.length(); i++) 
     {char currentChar = expression.charAt(i); 
     if(isOperator(currentChar)) 
       {while(!s.empty() && s.peek() != '(' && hasHigherPrecedence(s.peek(), currentChar)) 
         {output += s.peek(); 
         s.pop(); 
       } 
        s.push(currentChar); 
       } 
      else if(isOperand(currentChar)) 
      {output += currentChar; 
      } 
      else if(currentChar == '(') 
      {s.push(currentChar); 
      } 
      else if(currentChar == ')') 
      {while(!s.empty() && s.peek() != ')') 
      {output += s.peek(); 
      s.pop(); 
      } 
      } 
      while(!s.empty()) 
      {output += s.peek(); 
      s.pop(); 
      } 
    } return output; 
    } 

public boolean isOperator(char c) 
{ 
if(c =='+' || c=='-' || c=='/' || c=='*' || c== '^') 
    return true; 
return false; 
} 

public boolean isOperand(char c) 
{if(c>='0' && c<='9') return true; 
    if(c>= 'a' && c<= 'z') return true; 
    if(c>= 'A' && c<= 'Z') return true; 
    return false; 
} 

public int getOperatorWeight(char operator) 
{int weight = -1; 
    switch (operator) 
    {case '+': 
    case'-': 
    weight =1; 
    break; 

    case '*': 
    case '/': 
     weight = 2; 
     break; 

    case '^': 
     weight =3; 
    } 
    return weight; 
} 

public boolean hasHigherPrecedence(char operator1, char operator2) 
{ 
int op1 = getOperatorWeight(operator1); 
int op2 = getOperatorWeight(operator2); 
if(op1==op2) 
{if(isRightAssociative(operator1))return false; 
    else return true; 
} 
return op1> op2 ? true : false; 
} 

public boolean isRightAssociative(char op) 
{ 
if(op == '^') return true; 
return false; 
} 
} 

public class PostfixDemo 
{ 
    public static void main(String args[]) 
    { PostfixtoInfix2 j = new PostfixtoInfix2(); 
    System.out.print(j.PostfixtoInfix("3218+-")); 
    } 
} 
+1

Что "Выход" Вы ждете? Эта программа ничего не печатает ни по стандартной ошибке, ни по стандартным выводам – rmlan

+0

В методе PostfixtoInfix во второй-последней строке он должен возвращать переменную «output» строки. –

+0

Я не вижу попытки произвести вывод. Откуда вы ожидаете выхода? –

ответ

-2
public String postfix2Infix(String s) { 
    Stack<String> stack = new Stack<>(); 
    for (int i = 0, len = s.length(); i < len; ++i) { 
     char c = s.charAt(i); 
     if (isOperator(c)) { 
      String r = stack.pop(); 
      String l = stack.pop(); 
      stack.push("(" + l + c + r + ")"); 
     } else 
      stack.push(Character.toString(c)); 
    } 
    return stack.pop(); 
} 

public static void mai(String[] args) { 
    System.out.println(postfix2Infix("3218+-*")); // -> (3*(2-(1+8))) 
} 
+1

Почему бы не объяснить, что это такое? Объяснение гораздо ценнее кода. Используйте это как возможность обучения. – Makoto

Смежные вопросы