Advertisement
Guest User

Sum of All Values

a guest
May 30th, 2018
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.Scanner;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6.  
  7. /**
  8. * Created by IntelliJ IDEA.
  9. * User: LAPD
  10. * Date: 28.5.2018 г.
  11. * Time: 10:37 ч.
  12. */
  13. public class _14SumOfAllValues {
  14. public static void main(String[] args) {
  15. Scanner console = new Scanner(System.in);
  16.  
  17. String keys = console.nextLine();
  18. String text = console.nextLine();
  19.  
  20. Pattern startKeyPattern = Pattern
  21. .compile("^([A-Za-z_]+)\\d");
  22. Matcher startKeyMatcher = startKeyPattern
  23. .matcher(keys);
  24. Pattern endKeyPattern = Pattern
  25. .compile("\\d([A-Za-z_]+)$");
  26. Matcher endKeyMatcher = endKeyPattern
  27. .matcher(keys);
  28.  
  29. if (!startKeyMatcher.find() || !endKeyMatcher.find()) {
  30. System.out.println("<p>A key is missing</p>");
  31. return;
  32. }
  33.  
  34. String startKey = startKeyMatcher.group(1);
  35. String endKey = endKeyMatcher.group(1);
  36.  
  37. Pattern pattern = Pattern
  38. .compile(Pattern.quote(startKey)
  39. + "(\\d+[\\.]{0,1}\\d*?)"
  40. + Pattern.quote(endKey));
  41. Matcher matcher = pattern
  42. .matcher(text);
  43.  
  44. List<Double> nums = new ArrayList<>();
  45. int i = matcher.groupCount();
  46. while (matcher.find()) {
  47. nums.add(Double.parseDouble(matcher.group(1)));
  48. }
  49.  
  50. if (nums.isEmpty()) {
  51. System.out.println("<p>The total value is: <em>nothing</em></p>");
  52. } else {
  53. double sum = nums.stream()
  54. .reduce((a, b) -> a + b)
  55. .get();
  56.  
  57. if (sum == (int) sum) {
  58. System.out.printf("<p>The total value is: <em>" +
  59. "%d</em></p>%n", (int) sum);
  60. } else {
  61. System.out.printf("<p>The total value is: <em>" +
  62. "%.2f</em></p>%n", sum);
  63. }
  64. }
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement