1

I've been trying to make a simple calculator using JavaFX and I am very new to this. I have two TextFields and rest of the buttons are operators like +, -, *, /. The problem is that whenever I perform a calculation and press the equal, I get zero as a result. The calculator is not performing calculations for any of the operators. Kindly help me with this as I am unable to understand why is this happening. Below is the code of Controller file.

package application;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Button;

public class MainController {
    @FXML
    private Label result;

    @FXML 
    private TextField num1, num2 ;

    private String operator = "";
    private int number1, number2;
    //private boolean start = true;
    private Model model = new Model();
    
    @FXML
    public void processNumbers(ActionEvent event) {
        number1 = Integer.parseInt(num1.getText());
        number2 = Integer.parseInt(num2.getText());
    }
    
    @FXML
    public void processOperators(ActionEvent event) {
        String value = ((Button) event.getSource()).getText();
        if (!value.equals("?")) {
            if (!operator.isEmpty())
                return;
             
            operator = value;
        } else {
            if (operator.isEmpty())
                return;
            
            int output = model.calculate(number1, number2, operator);
            result.setText(String.valueOf(output));
            operator = "";
            //start = true;
        }
    }
}
  • If I understand well, when you make an operation and press `=`, you enter `processOperators()`, you validate the first condition `!value.equals("?")` and `operator` is not empty, so the only action performed by your calculator will be `return;`. I think that's why it doesn't make `result.setText(...)` – 0009laH Jul 26 '21 at 08:47
  • Thanks. So the problem is with the if else conditions. I'll check and update. – Mushahid Hussain Jul 26 '21 at 09:01

1 Answers1

2

I copied and ran your code. It works. The problem is that the flow is not intuitive (in my opinion).

First you need to enter values in both TextFields, i.e. num1 and num2. After you have entered the values, and the keyboard focus is on one of those TextFields, you need to press <ENTER> because pressing <ENTER> invokes method processNumbers because you set the onAction property for num1 and num2 in file Main.fxml

After entering the numbers and pressing <ENTER>, you press one of the operator buttons, i.e. / or * or + or -.

After you press one of the operator buttons, you press the ? button and the correct result is displayed.

By the way, I think that the Clear button does not work correctly. You should write a separate method that performs a clear operation and change the value of onAction for that button in the FXML file to the new method.

Abra
  • 19,142
  • 7
  • 29
  • 41