import java.util.Scanner; /* An instance of this class (which is stateless) has methods that, given ** an "expression-string" (i.e., a String describing an expression), builds ** a corresponding instance (of some child class) of the ExprTree class. ** One method handles expression-strings in prefix form, another handles ** those in postfix form, and another handles those in (fully-parenthesized) ** infix form. Here is an example of the same expression, rendered in each ** of those forms: ** ** infix: ( ( ( 3 + 7 ) * 2 ) - ( 24 / ( 1 + 5 ) ) ) (Fully-parenthesized) ** prefix: - * + 3 7 2 / 24 + 1 5 ** postfix: 3 7 + 2 * 24 1 5 + / - ** ** Note that, for ease of string processing, only expression-strings in ** which consecutive tokens are separated from each other by at least one ** space are considered to be valid. ** ** Authors: R. McCloskey and < STUDENT's NAME > ** Date: Feb. 2022 ** Collaborated With: ... ** Known Defects: ... */ public class ExprTreeBuilder { /* Returns a new instance of (some child of) the ExprTree class ** corresponding to that described by the given expression-string, ** which is assumed to be in prefix form. */ public ExprTree fromPrefix(String exprStr) { return null; // STUB! } /* Returns a stack containing the tokens of the given string. ** Of course, this stack, when repeatedly popped, will produce the ** tokens in reverse order of their appearance in the given string. */ private Stack stackedTokens(String str) { Stack stk = new StackViaArray(); Scanner scanner = new Scanner(str); while (scanner.hasNext()) { stk.push(scanner.next()); } return stk; } /* Returns a new instance of (some child of) the ExprTree class ** corresponding to that described by the given expression-string, ** which is assumed to be in postfix form. */ public ExprTree fromPostfix(String exprStr) { return null; // STUB! } /* Returns a new instance (of some child) of the ExprTree class, ** corresponding to that described by the given expression-string, ** which is assumed to be in (fully-parenthesized) infix form. */ public ExprTree fromInfix(String exprStr) { String LEFT_PAREN = "("; String RIGHT_PAREN = ")"; Stack operandStk = new StackViaArray(); Stack operatorStk = new StackViaArray(); Scanner scanner = new Scanner(exprStr); while (scanner.hasNext()) { String token = scanner.next(); // < REST OF LOOP BODY IS MISSING } if (operandStk.sizeOf() != 1) { System.out.println("ERROR: Infix expression is ill-formed"); } return operandStk.pop(); } // private methods // --------------- /* Reports whether the given string has the form of an integer literal. */ private boolean isIntLiteral(String str) { try { Integer.parseInt(str); return true; } catch (NumberFormatException e) { return false; } } }