Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class ExtendedCalculator
- {
- public static void main(String[] args)
- {
- Scanner scanner1 = new Scanner(System.in);
- String zahl;
- double ergebnis = 0;
- double wert = 0;
- double wert2 = 0;
- char vorzeichen;
- boolean schleife = true;
- String eingabeHilfe;
- eingabeHilfe = gibEingabeHilfe();
- System.out.println(eingabeHilfe);
- System.out.println(""); // Für die Übersicht eine freie Zeile.
- System.out.print(wert);
- while(schleife)
- {
- try
- {
- wert = ergebnis;
- zahl = scanner1.nextLine();
- Scanner scanner2 = new Scanner(zahl.substring(1));
- vorzeichen = zahl.charAt(0);
- wert2 = scanner2.nextDouble();
- switch (vorzeichen)
- {
- case '+':
- ergebnis = wert + wert2;
- break;
- case '-':
- ergebnis = wert - wert2;
- break;
- case '*':
- ergebnis = wert * wert2;
- break;
- case 'c':
- ergebnis = 0;
- break;
- case 'e':
- schleife = false;
- System.out.println("Eingabe beendet.");
- scanner2.close();
- break;
- case '/':
- if(wert2 != 0)
- {
- ergebnis = wert / wert2;
- }
- else
- {
- scanner2.close();
- throw new DivideByZeroException();
- }
- break;
- default:
- scanner2.close();
- throw new InvalidOperatorException();
- }
- if(schleife)
- {
- System.out.print(ergebnis);
- }
- }
- catch (InputMismatchException eInputMismatch)
- {
- System.out.println("Fehler - Bitte nur einen Operator und eine Zahl eingeben!");
- }
- catch (InvalidOperatorException eInvalid)
- {
- System.out.println(eInvalid.getMessage());
- }
- catch (DivideByZeroException eZero)
- {
- System.out.println(eZero.getMessage());
- }
- catch (Exception e)
- {
- System.out.println("Error! - Allgemeine Exception");
- e.printStackTrace();
- schleife=false;
- }
- }
- scanner1.close();
- }
- public static String gibEingabeHilfe ()
- {
- String hilfe = "Bitte geben Sie einen Operator und eine Zahl ein.\nBeenden mit 'e', Zahl auf 0 setzen mit 'c'.\nMögliche Operatoren: '+', '-', '*', '/'";
- return hilfe;
- }
- }
- class DivideByZeroException extends Exception
- {
- DivideByZeroException()
- {
- super("Error! - Man darf nicht durch 0 teilen!");
- }
- }
- class InvalidOperatorException extends Exception
- {
- InvalidOperatorException()
- {
- super("Ein ungültiger Operator wurde eingegeben!");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement