简体   繁体   中英

implementation of simple calculator

Create a program which simulates a very simple calculator

So I have been asked to implement an abstract class that represents binary (having 2 arguments) arithmetic expression

abstract class ArithmeticExpression {

    double binary1;
    double binary2;

    public abstract void evaluate ();

    public abstract void display ();

}

so then I created sub classes add, multiply, subtract, and divide. In subtract I have:

public class subtract extends ArithmeticExpression {
    // private double result;
    double binary1;
    double binary2;

    public subtract (double x, double y) {
        this.binary1 = x;
        this.binary2 = y;
    }

    public  void evaluate () {

        System.out.println("Expression: " + getsubX() + " - " + getsubY() + " = ");

        // return result;
    }

    public  void display () {

    }

    public double getsubX() {

    }

    public double getsubY() {

    }

Using the classes I should be able to represent any arbitrary expression, with no hard coding.

It is also said evaluate should return the result as double and display method should print the expression out in string. Am I on the right track? What am I missing here? The part I do not understand how it is able to represent any expression?

If you want to evaluate any expession inserted in form of

4 + 3 * ( 4 + 5)

You either need to create binary tree or stack and fill those values and operators in.

What I quite dont understand is your so called binary represented in double. If you want to have binary calc, you should use unsigned int or long (or any other type, that is not floating point)

Using your abstract ArithmeticExpression, here's what the Subtract class should look like. Java classes start with a capital letter.

public class Subtract extends ArithmeticExpression {
    double  result;

    public Subtract(double x, double y) {
        this.binary1 = x;
        this.binary2 = y;
    }

    @Override
    public void evaluate() {
        result = binary1 - binary2;
    }

    @Override
    public void display() {
        System.out.println("Expression: " + binary1 + 
                " - " + binary2 + " = " + result);
    }

}

You don't have to re-declare binary1 and binary2. They are instantiated in the abstract ArithmeticExpression class.

You do have to provide a double for the result. This should have been done in the abstract ArithmeticExpression class.

The evaluate() method is for evaluation.

The display() method is for display.

You don't have to define any other methods in your Subtract concrete class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM