such as \"(((3.2 * 25) - (4.3 / 2)) + 9.3)\", where each operand is a positive r
ID: 3545557 • Letter: S
Question
such as "(((3.2 * 25) - (4.3 / 2)) + 9.3)", where each operand is a positive real number, integer, or an expression,
and an operator is +, -, *, or /, with two operands and a pair of parentheses indicating the order of operations.
2. Build an expression tree from either a given (double or int) number alone, or a given (char) operator plus two sub-trees.
3. Evaluate a given expression tree.
4. Convert a given expression tree into a String, according to a given traversal order (preorder, inorder, or postorder).
hint: you need to show 3 lines one for each traversal
please write full java source
Explanation / Answer
import java.util.StringTokenizer; public class TokenExample { private static final String OPERATORS = "+-*/()"; private static boolean isOperator(char ch) { return OPERATORS.indexOf(ch) != -1; } public static void main(String[] args) { String infix="3.1+1.2"; StringBuilder postfix = new StringBuilder(); StringTokenizer infixTokens = new StringTokenizer(infix, OPERATORS+" ", true); while (infixTokens.hasMoreTokens()) { String nextToken = infixTokens.nextToken(); char firstChar = nextToken.charAt(0); if (Character.isJavaIdentifierStart(firstChar) || Character.isDigit(firstChar)) { postfix.append(nextToken); postfix.append(' '); System.out.println("real numbers: "+postfix); }else if (isOperator(firstChar)) { System.out.println("operator:"+firstChar); } } } }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.