Advertisement
Guest User

Connie ExtendedCalculaotr

a guest
Nov 21st, 2014
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class ExtendedCalculator
  4. {
  5. public static void main(String[] args)
  6. {
  7. Scanner scanner1 = new Scanner(System.in);
  8. String zahl;
  9. double ergebnis = 0;
  10. double wert = 0;
  11. double wert2 = 0;
  12. char vorzeichen;
  13. boolean schleife = true;
  14. String eingabeHilfe;
  15. eingabeHilfe = gibEingabeHilfe();
  16. System.out.println(eingabeHilfe);
  17. System.out.println(""); // Für die Übersicht eine freie Zeile.
  18. System.out.print(wert);
  19.  
  20. while(schleife)
  21. {
  22. try
  23. {
  24.  
  25.  
  26. wert = ergebnis;
  27. zahl = scanner1.nextLine();
  28. Scanner scanner2 = new Scanner(zahl.substring(1));
  29. vorzeichen = zahl.charAt(0);
  30. wert2 = scanner2.nextDouble();
  31. switch (vorzeichen)
  32. {
  33. case '+':
  34. ergebnis = wert + wert2;
  35. break;
  36. case '-':
  37. ergebnis = wert - wert2;
  38. break;
  39. case '*':
  40. ergebnis = wert * wert2;
  41. break;
  42. case 'c':
  43. ergebnis = 0;
  44. break;
  45. case 'e':
  46. schleife = false;
  47. System.out.println("Eingabe beendet.");
  48. scanner2.close();
  49. break;
  50. case '/':
  51. if(wert2 != 0)
  52. {
  53. ergebnis = wert / wert2;
  54. }
  55. else
  56. {
  57. scanner2.close();
  58. throw new DivideByZeroException();
  59. }
  60. break;
  61. default:
  62. scanner2.close();
  63. throw new InvalidOperatorException();
  64. }
  65. if(schleife)
  66. {
  67. System.out.print(ergebnis);
  68. }
  69. }
  70. catch (InputMismatchException eInputMismatch)
  71. {
  72. System.out.println("Fehler - Bitte nur einen Operator und eine Zahl eingeben!");
  73. }
  74. catch (InvalidOperatorException eInvalid)
  75. {
  76. System.out.println(eInvalid.getMessage());
  77. }
  78. catch (DivideByZeroException eZero)
  79. {
  80. System.out.println(eZero.getMessage());
  81. }
  82. catch (Exception e)
  83. {
  84. System.out.println("Error! - Allgemeine Exception");
  85. e.printStackTrace();
  86. schleife=false;
  87. }
  88. }
  89. scanner1.close();
  90. }
  91. public static String gibEingabeHilfe ()
  92. {
  93. String hilfe = "Bitte geben Sie einen Operator und eine Zahl ein.\nBeenden mit 'e', Zahl auf 0 setzen mit 'c'.\nMögliche Operatoren: '+', '-', '*', '/'";
  94. return hilfe;
  95. }
  96. }
  97.  
  98.  
  99. class DivideByZeroException extends Exception
  100. {
  101. DivideByZeroException()
  102. {
  103. super("Error! - Man darf nicht durch 0 teilen!");
  104. }
  105. }
  106.  
  107. class InvalidOperatorException extends Exception
  108. {
  109. InvalidOperatorException()
  110. {
  111. super("Ein ungültiger Operator wurde eingegeben!");
  112. }
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement