Taschenrechner programmiert (Java)?

Was würdet ihr verbessern rein von der Struktur.

import java.util.Scanner;
public class App {
    public static void main(String[] args) throws Exception {
        
        Scanner scanner = new Scanner(System.in);


        System.out.println("Bitte geben Sie erste Zahl ein: ");
        double zahl1 = scanner.nextDouble();


        System.out.println("Bitte geben Sie zweite Zahl ein: ");
        double zahl2 = scanner.nextDouble();


        System.out.println("Bitte geben Sie den Operator ein: ");
        char operator = scanner.next().charAt(0);


        System.out.println(taschenrechner(zahl1, zahl2, operator));


        
    }
    static double taschenrechner (double zahl1, double zahl2, char operator) {
            
        double ergebnis = 0.0;
        
        if (operator == '-') {
            ergebnis = zahl1 - zahl2;
        } else if (operator == '+') {
            ergebnis = zahl1 + zahl2;
        } else if (operator == '*') {
            ergebnis = zahl1 * zahl2;
        } else if (operator == '/') {
            ergebnis = zahl1 / zahl2;
        }
            return ergebnis;
    }
    
}


(1 votes)
Loading...

Similar Posts

Subscribe
Notify of
4 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
jo135
1 year ago

As already mentioned, a switch is best suited for mapping operators to operations, namely a switchexpression: https://dev.java/learn/language-basics/switch-expression/#producing-value

There are also other possibilities, such as a map on Lambdas, but this is perhaps too challenging at the moment.

You could also note that you do not consider any input errors at all. What if I run a wrong operator? What if I demand a division through 0?

verreisterNutzer
1 year ago
Reply to  jo135

I’m gonna build a try-catch reception today.

Chris102004
1 year ago

Change the if for the operator to a switch case instruction.

LeBonyt
1 year ago

Close me to Chris.

Switch case structure would be better.