Guest User

Untitled

a guest
Apr 24th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.61 KB | None | 0 0
  1. ```java
  2. import java.awt.dnd.InvalidDnDOperationException;
  3. import java.util.HashMap;
  4. import java.util.InputMismatchException;
  5. import java.util.Map;
  6. import java.util.Scanner;
  7.  
  8. public class Main {
  9. private static final char ADD = '+';
  10. private static final char SUB = '-';
  11. private static final char MULT = '*';
  12. private static final char DIV = '/';
  13. private static Map<Character, Double> operators = new HashMap<>();
  14.  
  15. public static void main(String... args) {
  16. printInfo();
  17. try {
  18. calculating();
  19. } catch (InputMismatchException e) {
  20. System.out.println("Invalid input, try enter numbers");
  21. } catch (InvalidDnDOperationException e) {
  22. System.out.println(e.getMessage());
  23. } catch (RuntimeException e) {
  24. System.out.println("Something went wrong" + e);
  25. }
  26. }
  27. private static void calculating(){
  28. Scanner sc = new Scanner(System.in);
  29. System.out.print("First number: ");
  30. double n1 = sc.nextDouble();
  31. System.out.print(" operator: ");
  32. sc.skip("\n");
  33. char operator = sc.nextLine().charAt(0);
  34. System.out.print("Second number: ");
  35. double n2 = sc.nextDouble();
  36. action(n1, n2);
  37. operatorValidator(operator);
  38. System.out.println("result: " + operators.get(operator));
  39. }
  40. private static void printInfo() {
  41. System.out.println("-------------Calculator-------------");
  42. System.out.println("enter first number and press enter,");
  43. System.out.println("after that enter operator and press enter,");
  44. System.out.println("enter second number and press enter");
  45. System.out.println("operators: + - * /");
  46. }
  47.  
  48. private static void operatorValidator(char operator) {
  49. if (operators.get(operator)==null) {
  50. throw new InvalidDnDOperationException("invalid operator: \"" + operator + "\"");
  51. }
  52. }
  53.  
  54. private static void action(double n1, double n2) {
  55. operators.put(ADD, addition(n1, n2));
  56. operators.put(SUB, subtraction(n1, n2));
  57. operators.put(MULT, multiply(n1, n2));
  58. operators.put(DIV, division(n1, n2));
  59. }
  60.  
  61. private static double addition(double n1, double n2) {
  62. return n1 + n2;
  63. }
  64.  
  65. private static double subtraction(double n1, double n2) {
  66. return n1 - n2;
  67. }
  68.  
  69. private static double multiply(double n1, double n2) {
  70. return n1 * n2;
  71. }
  72.  
  73. private static double division(double n1, double n2) {
  74. if (n2 == 0) {
  75. throw new InvalidDnDOperationException("divided by 0!!");
  76. }
  77. return n1 / n2;
  78. }
  79.  
  80. }
  81. ```
Add Comment
Please, Sign In to add comment