简体   繁体   中英

Getting result from calculator in Java

I have to calculate two inputs from separate JTextfields, pick an operator in a combobox and calculate the result based on the operator chosen. However, I get 0 as my answer. How can I calculate the result without getting 0?

private void jButton1_actionPerformed(ActionEvent e) {

    int x = Integer.parseInt(jTextField1.getText());
    int y = Integer.parseInt(jTextField2.getText());

    String Result = "0";
    jLabel4.setText(Result);
    int total = Integer.parseInt(Result);

    if(Operator.equals("+")) {
        total = x + y;
    }
    else if(Operator.equals("-")) {
        total = x - y;
    }
    else if(Operator.equals("*")) {
        total = x * y;
    }
    else if(Operator.equals("/")) {
        total = x / y;

    }

}

That's because you do not update jLabel4 after calculating the result.

After the if s you should have add another jLabel4.setText(Integer.toString(result));

From this code the jLabel4 is the result label.

What You are doing is first you assign to String Result with "0", and the you set this ("0") as text then you calculate.

What You should do is to calculate first and then set the result.

private void jButton1_actionPerformed(ActionEvent e) {

    int x = Integer.parseInt(jTextField1.getText());
    int y = Integer.parseInt(jTextField2.getText());

    int total = 0;

    if(Operator.equals("+")) {
        total = x + y;
    }
    else if(Operator.equals("-")) {
        total = x - y;
    }
    else if(Operator.equals("*")) {
        total = x * y;
    }
    else if(Operator.equals("/")) {
        total = x / y;

    }

    jLabel4.setText(String.valueOf(total));


}

You should separate the method into two parts: one responsible for the calculation of the result and the other for displaying. In addition to that you probably should use double, otherwise the division will give you unexpected results, ie 0 (eg in case of 1/2).

private void jButton1_actionPerformed(ActionEvent e) {

     int x = Integer.parseInt(jTextField1.getText());
     int y = Integer.parseInt(jTextField2.getText());

     double result = calculateResult(operator, x, y)
     jLabel4.setText(String.valueOf(result));
}

private double calculateResult(String operator, int x, int y) {

     if(operator.equals("+")) {
         total = x + y;
     }
     else if(operator.equals("-")) {
         total = x - y;
     }
     else if(operator.equals("*")) {
         total = x * y;
     }
     else if(operator.equals("/")) {
         total = x / y;

     }
     return total;
 }

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