0

this is the code in my "add" button for my calculator. Im having problem in some data type validations: Example: 9.2+3.2 = 12.4, in this way my calculator works fine. but if you entered integer first like this: 9 + 3.2, the result will only be 3.2. How do you think can i parse the first value if the decimal exists on the second value?

private void btn_AddActionPerformed(java.awt.event.ActionEvent evt) {                                        

    //FOR DOUBLE CALCULATION
    if(ta_DisplayField.getText().contains(".") || c_History.contains(".")){
        c_Operator = '+';
        c_Container = "+";
        c_History = c_History + "+";
        ta_History.setText(c_History);

        c_totalDouble = (double)c_totalInt + Double.parseDouble(ta_DisplayField.getText());
        ta_DisplayField.setText(c_totalDouble + "");

        }
    }
    //FOR INTEGER CALCULATION
    else{
        c_Operator = '+';
        c_Container = "+";
        c_History = c_History + "+";
        ta_History.setText(c_History);

        c_totalInt = c_totalInt + Integer.parseInt(ta_DisplayField.getText());
        ta_DisplayField.setText(c_totalInt + "");

        }
    }
}
  • Unrelated to the question, but you should really consider refactoring your code here to avoid this duplication of code ;) – Joffrey Aug 23 '17 at 07:47
  • I would suggest creating an arithmetic expression and evaluating it when '=' is pressed. In that way, your code will be very much generic. – Ashish Lohia Aug 23 '17 at 09:20

1 Answers1

0

You're reinventing the bulb. The solution is much simpler :

String s = "9 + 3.2";

String[] split = s.split("\\+");

Double result = Arrays.stream(split).mapToDouble(Double::parseDouble).sum();

System.out.println(result);
Schidu Luca
  • 3,897
  • 1
  • 12
  • 27
  • True. But adding a little explaination would be better. I don't think that the OP is familiar with the concept of functional programming introduced in Java 8. – MC Emperor Aug 23 '17 at 07:47
  • The OP is doing many more things here, and the piece of code we have does not tell us anything about how he uses the data he stored in all these variables/fields. I agree that the code can be heavily simplified, but we can't really know how unless we have the whole picture. – Joffrey Aug 23 '17 at 07:49
  • good day si joffrey, ive already minimize my code to point out what i want to happen. – Mark Lorenz Balajadia Aug 23 '17 at 07:57
  • c_totalInt = container for total sum of integer c_totalDouble = container for total double – Mark Lorenz Balajadia Aug 23 '17 at 07:58