-1

Between lines 201 and 208 I'm trying to make the decimal point. After the decimal is made, making any calculation the code crashes.

JButton btnsum = new JButton("=");
btnsum.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        num2 = Integer.parseInt(textField.getText());

        switch(operator) {
        case 1: result = num1 / num2;
        break;
        case 2: result = num1 * num2;
        break;
        case 3: result = num1 - num2;
        break;
        case 4: result = num1 + num2;
        break;
        case 5: result = Math.pow(num1,num2);
        break;


        default: result = 0.0;
            }

        textField.setText(""+result);
}
});


JButton btncol = new JButton(".");
    btncol.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String str = textField.getText();
            str += (".");
            textField.setText(str);

        }
});  

Everything else is fine and dandy but this decimal point is not working.

Samuel
  • 52
  • 7
  • 2
    You're currently using `Integer.parseInt` to parse the number - that's not going to work when you're trying to parse (say) "2.5". I would suggest considering parsing as a `BigDecimal`. – Jon Skeet Mar 29 '19 at 08:58

1 Answers1

0

Problem is with this line Integer.parseInt(textField.getText());

You can parse to Float or Double and then calculate/process.

But problem in Float and Double is Possible Loss of Precision. for more info on this, you could read this answer

To avoid that precision loss, you can use BigDecimal in Java. But working with BigDecimal might get complex for you if you haven't used that before. But you'll learn more about machine and their processing behavior for sure.

Note:

Systems where precision really matters like Banking Application, Monetary Calculations, etc, you must use BigDecimal for more accurate result.

miiiii
  • 1,580
  • 1
  • 16
  • 29