[OFFEN] Taschenrechner-Verstehe Code nicht

  • 4 Antworten
  • Letztes Antwortdatum
A

androidcoder

Neues Mitglied
0
Hallo,
Wozu bzw. für was ist die Variable pendingOperation da?
Wozu brauchen wir diese zwei Code Snippet hier? Was wird hier gemacht?

1)
Code:
    if (pendingOperation.equals("=")) {
         pendingOperation = operation;
     }

2)
Code:
    switch (pendingOperation) {
        case "=":
            operand1 = operand2;
            break;


Ganzer Code:
Code:
    private void performOperation(String value, String operation){
        if (null == operand1) {
            operand1 = Double.valueOf(value);
        } else {
            operand2 = Double.valueOf(value);
    
           if (pendingOperation.equals("=")) {
                pendingOperation = operation;
            }
            switch (pendingOperation) {
                case "=":
                    operand1 = operand2;
                    break;
                case "/":
                    if (operand2 == 0) {
                        operand1 = 0.0;
                    } else {
                        operand1 /= operand2;
                    }
                    break;
                case "*":
                    operand1 *= operand2;
                    break;
                case "-":
                    operand1 -= operand2;
                    break;
                case "+":
                    operand1 += operand2;
                    break;
            }
        }
    
        result.setText(operand1.toString());
        newNumber.setText("");
    
    }


Vielen Dank für eure Hilfe
 
Niemand eine Idee?
 
Das ist eine pendingOperation ist einfach eine unglückliche Benennung einer Variable. Bei dem Taschenrechner gibt es Opperatoren (+,-,=* usw). In der Methode wird der String (bzw. Operator) in der switch-case Abfrage ausgewertet.
 
Ok, könntest du aber auch code 1 und code 2 erklären?
 
Der Code hat nicht mit Androidprogrammierung zu tun, sondern berührt die Grundlagen der Programmierung. 1) ist einfach eine if-Abfrage. Wenn pendingOperation gleich (equals) den String "=" ist, dann weise der Variable "pendingOperation" den Wert der Variable Operation zu.
2) Macht im Prinzip das gleiche, nur hier wird eine switch-case Abfrage verwendet.

Und sonst lese bitte folgende Dokumentation durch:
If-Anweisung in Java
und
Javabeginners - switch-case-Verzweigung
 
Zurück
Oben Unten