簡體   English   中英

將Postfix表達式轉換為infix並計算后綴並給出答案

[英]Convert a Postfix expression to infix and calculate the postfix and give the answer

我一直在研究該程序,以接收后綴表達式,計算並打印出答案,並將其轉換為中綴表達式。 我已經將計算部分工作了。 例如,如果我輸入2 2 +(說明間距),它將得到4。但是,對於其中的中綴部分,它將輸出2+。 然后,我嘗試了它,沒有任何間距。 我輸入了22+。 后綴不起作用,但是中綴正確打印出來。 因此,我不確定如何修復此部分。 這是我的代碼。

 import java.util.NoSuchElementException;
 import java.util.Stack;
 public class ExpressionTree 
 {

private final String postfix;
private TreeNode root;

/**
 * Takes in a valid postfix expression and later its used to construct the expression tree.
 * The posfix expression, if invalid, leads to invalid results 
 * 
 * @param postfix   the postfix expression.
 */
public ExpressionTree(String postfix) 
{
    if (postfix == null) { throw new NullPointerException("The posfix should not be null"); }
    if (postfix.length() == 0)  { throw new IllegalArgumentException("The postfix should not be empty"); } 
    this.postfix = postfix;
}

private static class TreeNode 
{
    TreeNode left;
    char ch;
    TreeNode right;

    TreeNode(TreeNode left, char ch, TreeNode right) {
        this.left = left;
        this.ch = ch;
        this.right = right;
    }
}


private boolean isOperator(char c) {
    return c == '+' || c == '-' || c == '*' || c == '/';
}


/**
 * Constructs an expression tree, using the postfix expression
 */
public void createExpressionTree() 
{
    final Stack<TreeNode> nodes = new Stack<TreeNode>();
    for (int i = 0; i < postfix.length(); i++) 
    {
        char ch  = postfix.charAt(i);
        if (isOperator(ch)) 
        {
           TreeNode rightNode = nodes.pop();
           TreeNode leftNode = nodes.pop();
           nodes.push(new TreeNode(leftNode, ch, rightNode));
        } else 
        {
            nodes.add(new TreeNode(null, ch, null));
        }
    }
    root = nodes.pop();
}
/**
 * Returns the infix expression
 * 
 * @return  the string of infix.
 */
public String infix() 
{
    if (root == null) 
    {
        throw new NoSuchElementException("The root is empty, the tree has not yet been constructed.");
    }
    final StringBuilder infix = new StringBuilder();
    inOrder(root, infix);
    return infix.toString();
}

private void inOrder(TreeNode node, StringBuilder infix) {
    if (node != null) {
        inOrder(node.left, infix);
        infix.append(node.ch);
        inOrder(node.right, infix);
    }
}
public Double evaluate(String postfix)
{
    Stack<Double> s = new Stack<Double>();
    char[] chars = postfix.toCharArray();
    int N = chars.length;
    for(int i = 0; i < N; i++)
    {
        char ch = chars[i];
        if(isOperator(ch))
        {
            switch(ch)
            {
            case '+': s.push(s.pop() + s.pop());     break;
            case '*': s.push(s.pop() * s.pop());     break;
            case '-': s.push(-s.pop() + s.pop());    break;
            case '/': s.push(1 / s.pop() * s.pop()); break;
            }
        }
        else if(Character.isDigit(ch)) 
        {
            s.push(0.0);
            while (Character.isDigit(chars[i]))
                s.push(10.0 * s.pop() + (chars[i++] - '0'));
    }
    } 
        return s.pop();

    }
    }

這是我的測試人員:

      import java.util.Scanner;
      public class ExpressionTester

       public static void main(String[] args) 
      {
    Scanner sc = new Scanner(System.in);
    while(true)
    {
    System.out.println("");
    String pf = sc.nextLine();
    ExpressionTree eT = new ExpressionTree(pf);
    eT.createExpressionTree();
    System.out.println("The infix: " + eT.infix() );
    System.out.println(eT.evaluate(pf));
    }

    }
    }

任何幫助將不勝感激,因為我真的不知道如何解決此問題,我已經接近完成。

if (isOperator(ch))
{
    TreeNode rightNode = nodes.pop();
    TreeNode leftNode = nodes.pop();
    nodes.push(new TreeNode(leftNode, ch, rightNode));
}
else
{
    nodes.add(new TreeNode(null, ch, null));
}

您正在將空格節點放入樹中。 嘗試這個:

if (isOperator(ch))
{
    TreeNode rightNode = nodes.pop();
    TreeNode leftNode = nodes.pop();
    nodes.push(new TreeNode(leftNode, ch, rightNode));
}
else if (!Character.isWhitespace(ch))
{
    nodes.add(new TreeNode(null, ch, null));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM