lots of exercises in java... from https://github.com/exercism/java

WordProblemSolver.java 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3. final class WordProblemSolver {
  4. private static final String INTEGER_REGEX_STRING = "(-?\\d+)";
  5. private static final String BINARY_OPERATION_REGEX_STRING = "(plus|minus|multiplied by|divided by)";
  6. private static final String VALID_QUESTION_REGEX_STRING =
  7. "^What is " + INTEGER_REGEX_STRING +
  8. "( " + BINARY_OPERATION_REGEX_STRING + " " + INTEGER_REGEX_STRING + ")+" +
  9. "\\?$";
  10. int solve(final String wordProblem) {
  11. if (!wordProblem.matches(VALID_QUESTION_REGEX_STRING)) {
  12. throw new IllegalArgumentException("I'm sorry, I don't understand the question!");
  13. }
  14. final Matcher initialValueMatcher = Pattern.compile(INTEGER_REGEX_STRING).matcher(wordProblem);
  15. initialValueMatcher.find();
  16. int result = Integer.parseInt(initialValueMatcher.group());
  17. final Matcher operationAndValueMatcher
  18. = Pattern.compile(BINARY_OPERATION_REGEX_STRING + " " + INTEGER_REGEX_STRING).matcher(wordProblem);
  19. while (operationAndValueMatcher.find()) {
  20. result = applyBinaryOperation(
  21. result,
  22. operationAndValueMatcher.group(1),
  23. Integer.parseInt(operationAndValueMatcher.group(2)));
  24. }
  25. return result;
  26. }
  27. private int applyBinaryOperation(
  28. final int firstValue,
  29. final String operationDescription,
  30. final int secondValue) {
  31. switch (operationDescription) {
  32. case "plus":
  33. return firstValue + secondValue;
  34. case "minus":
  35. return firstValue - secondValue;
  36. case "multiplied by":
  37. return firstValue * secondValue;
  38. case "divided by":
  39. return firstValue / secondValue;
  40. default:
  41. throw new IllegalArgumentException("This branch should never be executed.");
  42. }
  43. }
  44. }