Question

I am trying throw an exception when an invalid operator is typed (such as $, # &). Also when a number is divided by zero. Although the application is breaking. I was wondering if I am doing this right or not.

package PrefixCalc;

import java.util.Scanner;

public class Expressions {

    public static class IllegalExpressionException extends RuntimeException {

        public IllegalExpressionException(String message) {
            super("Illegal expression: " + message);
        }
    }

    private static class Calculator {

        private final boolean Calc; // ?Is this a Calc? else internal
        private final char op; // For an internal node, the operator
        private double value; // For a Calc, the value
        private Calculator left, // Left subexpression (internal node)
                right; // Right subexpression
// Bare-bones constructor

        private Calculator(boolean Calc, char op, double value) {
            this.Calc = Calc;
            this.op = op;
            this.value = value;
            this.left = null; // Empty to start
            this.right = null;
        }
// For Calc nodes, show the value; for internal, the operator.

        public @Override
        String toString()// Overrides Object.toString, must be public.
        {
            return Calc ? Double.toString(value) : Character.toString(op);
        }
    }
    Calculator root = null;

    public Expressions(Scanner input) {
        root = build(input);
    }

    /**
     * Based on a white-space delimited prefix expression, build the
     * corresponding binary expression tree.
     *
     * @param input The scanner with the expression
     * @return reference to the corresponding binary expression
     */
    private Calculator build(Scanner input) {

        boolean Calc;
        String token;
        double value;
        Calculator node;
        Calc = input.hasNextDouble();
        if (Calc) {
            try {
                value = input.nextDouble();
                node = new Calculator(Calc, '\0', value);
            } catch (IllegalExpressionException message) {
                throw new IllegalExpressionException("Illegal Expression Syntex!");
            }
        } else {
            try {
                token = input.next();
                node = new Calculator(Calc, token.charAt(0), 0.0);
                node.left = build(input);
                node.right = build(input);
            } catch (IllegalExpressionException message) {
                throw new IllegalExpressionException("Illegal Expression Syntex!");

            }

        }
        return node;


    }

    /**
     * Show the expression tree as a prefix expression.
     */
    public void showPreFix() {
        showPreFix(root);
        System.out.println();
    }
// Prefix expression is the result of a pre-order traversal

    private void showPreFix(Calculator node) {
        while (node != null) {
            System.out.print(node + " ");
            showPreFix(node.left);
            node = node.right; // Update parameter for right traversal
        }
    }

    /**
     * Show the expression tree as a parenthesized infix expression.
     *
     */
    public void showInFix() {
        showInFix(root);
        System.out.println();
    }
// Parenthesized infix requires parentheses in both the
// pre-order and post-order positions, plus the node
// itself in the in-order position.

    private void showInFix(Calculator node) {
        if (node != null) {

            if (!node.Calc) {
                System.out.print("( "); // Pre-order position
            }
            showInFix(node.left);
            System.out.print(node + " "); // In-order position
            showInFix(node.right);
            if (!node.Calc) // Post-order position
            {
                System.out.print(") ");
            }
        }
    }


    public double evaluate() {
        return root == null ? 0.0 : evaluate(root);
    }


    private double evaluate(Calculator node) throws ArithmeticException {
        double result; // Value to be returned
        if (node.Calc) // Just get the value of the Calc
        {
            result = node.value;
        } else {

            double left, right;
            char operator = node.op;
            if(operator != '-' && operator != '+' && operator != '/' && operator != '*') {
                        throw new ArithmeticException("Illegal Arthematic Syntex!" + operator);
                       // break;
                    }
// Capture the values of the left and right subexpressions
            left = evaluate(node.left);
            right = evaluate(node.right);
// Do the arithmetic, based on the operator
            switch (operator) {
                case '-':
                    result = left - right;
                    break;
                case '*':
                    result = left * right;
                    break;
                case '+':
                    result = left + right;
                    break;
                case '/':

                    result = left / right;

                    if (right == 0) {
                        throw new ArithmeticException("Division by zero!");
                    }
                    break;

                default:
                    throw new ArithmeticException("Illegal Arthematic Operation" + operator);
            }
        }
// Return either the Calc's value or the one we just calculated.
        result = Math.round(result * 100.0) / 100.0;
        return result;

    }
}

The output when an invalid operator is typed is:

Exception in thread "main" java.lang.ArithmeticException: Illegal Arthematic Syntex!$ at PrefixCalc.Expressions.evaluate(Expressions.java:152) at PrefixCalc.Expressions.evaluate(Expressions.java:135) at PrefixCalc.PrefixCalc.main(PrefixCalc.java:25) Java Result: 1

Was it helpful?

Solution

From your code I see exceptions are already being thrown by Java run time. You have to handle them and show appropriate error message to the user.

However, right thing to do is to validate the user input before executing the expression. That will avoid making the call, getting the exception and handling it later. Validate the user inputs and show a message to the user if the inputs are not correct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top