Estoy tratando de escribir una aplicación de calculadora con la ayuda de Javafx y he golpeado un bloqueo de carretera. Estoy tratando de escribir un método que hace el cálculo real, pero estoy teniendo alguna dificultad. El método que escribí está en el código a continuación. Hace la primera multa del cálculo, pero cuando intentas agregar al cálculo todo sale mal. Siento que he ido de escribir tan mal. Cualquier ayuda sería muy apreciada.

El método en cuestión:

public void calculate() {
        if(result != 0) {
            System.out.println(finalResult);
            switch (operatorPressed) {
                case '+':
                    result = result + numberPressed;
                    setFinalResult(result);
                    System.out.println(operatorPressed);
                case '-':
                    result = result - numberPressed;
                case '*':
                    result = result * numberPressed;
                case '/':
                    result = result / numberPressed;
            }
        }
        else {
            result = numberPressed;
        }
    }

Clase completa de calculadora:

package sample;

public class CalculatorEngine {

    

    private double numberPressed = 0;
    private double result = 0;
    public double finalResult;
    public char operatorPressed;


    public double getFinalResult() {
        return finalResult;
    }

    public void setFinalResult(double finalResult) {
        this.finalResult = finalResult;
    }

    public void setNumberPressed(double number) {
        numberPressed = number;
    }

    public void setOperatorPressed(char operator) {
        operatorPressed = operator;
    }

    public void calculate() {
        if(result != 0) {
            System.out.println(finalResult);
            switch (operatorPressed) {
                case '+':
                    result = result + numberPressed;
                    setFinalResult(result);
                    System.out.println(operatorPressed);
                case '-':
                    result = result - numberPressed;
                case '*':
                    result = result * numberPressed;
                case '/':
                    result = result / numberPressed;
            }
        }
        else {
            result = numberPressed;
        }
    }
}

Clase de controlador completo:

package sample;

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.net.URL;


public class Controller {
    @FXML
    private Button btnSix;

    @FXML
    private Button btnEight;

    @FXML
    private Button btnNine;

    @FXML
    private Button btnDivide;

    @FXML
    private Button btnFour;

    @FXML
    private Button btnFive;

    @FXML
    private Button btnSeven;

    @FXML
    private Button btnMultiply;

    @FXML
    private Button btnOne;

    @FXML
    private Button btnTwo;

    @FXML
    private Button btnThree;

    @FXML
    private Button btnSubtract;

    @FXML
    private Button btnZero;

    @FXML
    private Button btnDecimalPoint;

    @FXML
    private Button btnEquals;

    @FXML
    private Button btnPlus;

    @FXML
    private Label txtCalcDisplay;

    private ArrayList<String> outputList = new ArrayList<>();
    private CalculatorEngine engine = new CalculatorEngine();
    private String output = "";
    private double finalResult;

    private final int oneValue = 1;
    private final int twoValue = 2;
    private final int threeValue = 3;
    private final int fourValue = 4;
    private final int fiveValue = 5;
    private final int sixValue = 6;
    private final int sevenValue = 7;
    private final int eightValue = 8;
    private final int nineValue = 9;
    private final int zeroValue = 0;


    //@Override
    //public void initialize(URL url, ResourceBundle resourceBundle) {
    //}

    public void organiseOutput()
    {
        for(int i = 0; i <= outputList.size()-1; i++) {
           output = output.concat(outputList.get(i));
        }
    }

    public void displayOutput()
    {
        if(outputList.get(outputList.size()-1).equals("=")) {
            txtCalcDisplay.setText(String.valueOf(engine.getFinalResult()));
        }
        else if(outputList.get(outputList.size()-1).equals("-") || outputList.get(outputList.size()-1).equals("+") || outputList.get(outputList.size()-1).equals("*") || outputList.get(outputList.size()-1).equals("/")) {
            txtCalcDisplay.setText("");
        }
        else {
            //output = "";
            txtCalcDisplay.setText("");
            txtCalcDisplay.setText(output);
        }

    }

    public void onOneButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("1");
        output = String.valueOf(oneValue);
        displayOutput();
        engine.setNumberPressed(oneValue);
        engine.calculate();

    }

    public void onTwoButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("2");
        output = String.valueOf(twoValue);
        displayOutput();
        engine.setNumberPressed(twoValue);
    }

    public void onThreeButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("3");
        output = String.valueOf(threeValue);
        displayOutput();
        engine.setNumberPressed(threeValue);
    }

    public void onFourButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("4");
        output = String.valueOf(fourValue);
        displayOutput();
        engine.setNumberPressed(fourValue);
    }

    public void onFiveButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("5");
        output = String.valueOf(fiveValue);
        displayOutput();
        engine.setNumberPressed(fiveValue);
    }

    public void onSixButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("6");
        output = String.valueOf(sixValue);
        displayOutput();
        engine.setNumberPressed(sixValue);
    }

    public void onSevenButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("7");
        output = String.valueOf(sevenValue);
        displayOutput();
        engine.setNumberPressed(sevenValue);
    }

    public void onEightButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("8");
        output = String.valueOf(eightValue);
        displayOutput();
        engine.setNumberPressed(eightValue);
    }

    public void onNineButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("9");
        output = String.valueOf(nineValue);
        displayOutput();
        engine.setNumberPressed(nineValue);
    }

    public void onZeroButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("0");
        output = String.valueOf(zeroValue);
        displayOutput();
        engine.setNumberPressed(zeroValue);
    }

    public void onAddButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("+");
        output = "+";
        displayOutput();
        engine.setOperatorPressed('+');
        engine.calculate();
    }

    public void onMinusButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("-");
        output = "-";
        displayOutput();
        engine.setOperatorPressed('-');
        engine.calculate();
    }

    public void onDivideButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("/");
        output = "/";
        displayOutput();
        engine.setOperatorPressed('/');
        engine.calculate();
    }

    public void onMultiplyButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("*");
        output = "*";
        displayOutput();
        engine.setOperatorPressed('*');
        engine.calculate();
    }

    public void onDecimalButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add(".");
        output = ".";
        displayOutput();
        engine.setOperatorPressed('.');
        engine.calculate();
    }

    public void onEqualsButtonClicked(ActionEvent event) throws IOException
    {
        outputList.add("=");
        output = "=";
        engine.calculate();
        displayOutput();
    }
}

0
Leonard 8 jun. 2021 a las 18:18

2 respuestas

La mejor respuesta

Necesita un break; después de cada caso.

 public void calculate() {
    if(result != 0) {
        System.out.println(finalResult);
        switch (operatorPressed) {
            case '+':
                result = result + numberPressed;
                setFinalResult(result);
                System.out.println(operatorPressed);
                break;
            case '-':
                result = result - numberPressed;
                break;
            case '*':
                result = result * numberPressed;
                break;
            case '/':
                result = result / numberPressed;
                break;
        }
    }
3
Lucadmin 8 jun. 2021 a las 15:50

La declaración de switch de tradición necesita un break: en el final de cada caso. Hay una sintaxis más nueva desde Java 12, utilizando -> en lugar de :.

        switch (operatorPressed) {
            case '+' ->
                result += numberPressed;
                setFinalResult(result);
                System.out.println(operatorPressed);
            case '-' ->
                result -= numberPressed;
            case '*' ->
                result *= numberPressed;
            case '/' ->
                result /= numberPressed;
        }

En el código original A - se reduciría a * y /.

Otro consejo: switch también puede operar en cadenas: switch ("...") { case "CE" -> ....

2
Joop Eggen 8 jun. 2021 a las 15:46