Java Simple Calculator

廉价感情. 提交于 2019-12-05 11:59:03

Get the calculation as a string and use ScriptEngine:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
t.setText(engine.eval(calculation_String));

First in Java classes should be start with first letter UpperCase Java Code Conventions

Second instead of creating a method for each number

void bpressed(ActionEvent e, Integer number) {
    if (b) {
        t.setText(null);
        b = false;
        t.setText(t.getText() + number);
    } else {
        t.setText(t.getText() + number);
    }
}

Use declarative names for things, what is b? it is not intuitive, class name should be Calculator or something like this, code must be readable for humans.

Related to your question you can have a partialResult when some operation is in progress. For example:

you declare

private double partialResult=0D;

and a method something like this

private void calculatePartialResult(Integer numberSelected){
      //choose depends on action
      partialResult op= numberSelected;  (where op in + - * /)    
  }

When doing 1 + 2 + 3 your current code is doing :

User tap on '1' '+' 
op1 = 1.0, action = '+' 

User tap on '2' '+'
op1 = 2.0, action = '+'

User tap on '3' '='
op1 = 2.0, op2 = 3.0, action = '+'

doCal() displays the result of op1 + op2 which is 5

I think that you should use op1 to store the value of the previous calculations to obtain the behavior you are expecting.

Here is how I would do it.

Instead of calling doCal() only when equal is pressed, call it every time an operator is pressed, at the start of the operator action handler. Store the value inside of op2, to allow the calculation to take place :

void bPlusPressed(ActionEvent e) {
    op2 = Double.parseDouble(t.getText());
    doCal();
    b = true;
    action = '+';
}

(Apply the same changes for the other operators).

Inside of doCal(), store the result into op1 instead of displaying it :

void doCal() {
    // No need to use a class attribute for result, prefer a local variable.
    final double result;
    switch (action) {
        case '+': result = op1 + op2; break;
        case '-': result = op1 - op2; break;
        case '*': result = op1 * op2; break;
        case '/': result = op1 / op2; break;
        // When no action is set, simply copy op2 into op1
        default: result = op2;
    }
    op1 = result;
}

Then, change bEqPressed() to make it display op1 and reset the value of action :

void bEqpressed(ActionEvent e) {
    op2 = Double.parseDouble(t.getText());
    doCal();
    t.setText(String.valueOf(result));
    action = '\0';
}

This should do the trick.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!