Snippets

Ettar Java - Rechner

Created by Ettar last modified
    public static void main(String[] ARGS){
        Scanner s = new Scanner (System.in);
        calculate(s);
        s.close();
    }    
    
    public static void calculate(Scanner s) {
        boolean bool = false;
        double a=0,b=0;
        System.out.println("Wähle eine Rechenoperation aus. Zur Auswhl stehen: +,-,/,");
        String operationszeichen = s.next();

        while(!operationszeichen.matches("[+-/*]")){
                System.out.println("Eingabe nicht verstanden. Bitte wähle eine gültige Rechenoperation aus.");
                operationszeichen = s.next();

        }

        System.out.println("Eingabe bestätigt.");

        do{
            try{
                System.out.println("Nun gib zwei Zahlen ein, mit denen gerechnet werden soll");
                a = Double.parseDouble(s.next());
                b = Double.parseDouble(s.next());
                if(b==0 && operationszeichen.equals("/")){
                    System.out.println("Teilen durch 0 nicht erlaubt");
                }
                else{
                    bool = true;
                }
            }catch (NumberFormatException e){
                bool = false;
                System.out.println("Bitte Zahlen eingeben!");
            }
        }while(!bool);

        switch(operationszeichen){
            case "+":
                a+=b;
                break;
            case "-":
                a-=b;
                break;
            case "/":
                a/=b;
                break;
            case "*":
                a*=b;
                break;
        }

        System.out.println("Das Ergebnis lautet: " + a);
    }

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.