开发者

Getting result from calculator in Java

I have to calculate t开发者_JAVA技巧wo 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 ifs 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, i.e. 0 (e.g. 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;
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜