Java Calculator minus error

Take a look at your btMinusActionPerformed method:

private void btMinusActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // minus button
    firstNumber = Float.parseFloat(calScreen.getText());
    OP = "-";
    numberClick += 1;
    if (!calScreen.getText().equals("-") && numberClick == 2){
    else {
        calScreen.setText("-"); // <- What does this do?

Then take a look at the btEqualActionPerformed method:

private void btEqualActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // Result
    // What is getText() going to return if you pressed the minus button?
    secondNumber = Float.parseFloat(calScreen.getText());
    { ... } // Omitted for brevity

Follow that through logically and you’ll notice that when you click the buttons for 1, -, and 2, you will read in 1 and -2. You’re already storing the operand in OP, so what you’ll do is 1 - (-2), which does actually equal 3. Your problem is in btMinusActionPerformed – that’s where you need to fix your code.

Additionally, your operations regular expression isn’t quite correctly defined. You haven’t escaped either the - or the ., so they aren’t going to work in the way that you expect them to.

operations = "[+|\\-|x""0|\\.]",
//               ^         ^
// Note the escape characters at these two locations

That should make your regex work in the way you intended for it to work.

An alternative solution would be to remove:


From your btMinusActionPerformed method (and the corresponding lines from the other three operator’s methods), which would mean that the regex wasn’t necessary.

Leave a Comment