Advertisement
Chiddix

SmartCalc homework

Aug 29th, 2016
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.38 KB | None | 0 0
  1. package smartcalc;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.Scanner;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8.  
  9. public final class SmartCalc {
  10.  
  11.     private static final Pattern OPERAND_PATTERN = Pattern.compile("\\d+(?:\\.\\d+)?");
  12.     private static final Pattern OPERATION_PATTERN = Pattern.compile("add|subtract|multiply|divide");
  13.  
  14.     public static void main(final String[] args) {
  15.         try (final Scanner scanner = new Scanner(System.in)) {
  16.             String input;
  17.             while (!(input = scanner.nextLine()).equals("quit")) {
  18.                 try {
  19.                     final List<String> operands = allMatches(OPERAND_PATTERN, input);
  20.                     final List<String> operations = allMatches(OPERATION_PATTERN, input);
  21.                     if (operands.size() == 2 && operations.size() == 1) {
  22.                         final double result = applyOperation(Double.parseDouble(operands.get(0)), Double.parseDouble(operands.get(1)), operations.get(0));
  23.                         System.out.println("=" + result);
  24.                         break;
  25.                     } else {
  26.                         throw new IllegalStateException("Illegal operand or operation size");
  27.                     }
  28.                 } catch (final IllegalStateException e) {
  29.                     System.out.println("You inputed more than two operands or more than one operations. Please try again or type 'quit' to stop");
  30.                 }
  31.             }
  32.         }
  33.     }
  34.    
  35.     private static List<String> allMatches(final Pattern pattern, final String input) {
  36.         final Matcher matcher = pattern.matcher(input);
  37.         final List<String> operands = new ArrayList<>();
  38.         while (matcher.find()) {
  39.             operands.add(matcher.group());
  40.         }
  41.         return operands;
  42.     }
  43.    
  44.     private static double applyOperation(final double firstOperand, final double secondOperand, final String operation) {
  45.         switch (operation) {
  46.             case "add":
  47.                 return firstOperand + secondOperand;
  48.             case "subtract":
  49.                 return firstOperand - secondOperand;
  50.             case "multiply":
  51.                 return firstOperand * secondOperand;
  52.             case "divide":
  53.                 return firstOperand / secondOperand;
  54.         }
  55.         // TODO: throw exception
  56.         return 0;
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement