Advertisement
valchak

Sum of All Values

Oct 1st, 2017
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4.  
  5. public class p14_Sum_of_All_Values {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.         String keyString = scanner.nextLine();
  10.         String textString = scanner.nextLine();
  11.         String startKey = "";
  12.         String endKey = "";
  13.  
  14.         Pattern regexStartKeyString = Pattern.compile("^([A-Za-z_]+)(?=\\d)");
  15.         Matcher matcherStartKeyString = regexStartKeyString.matcher(keyString);
  16.  
  17.         if (matcherStartKeyString.find()) {
  18.             startKey = matcherStartKeyString.group(1);
  19.         } else {
  20.             System.out.println("<p>A key is missing</p>");
  21.             return;
  22.         }
  23.  
  24.         Pattern regexEndKeyString = Pattern.compile("(?<=\\d)([A-Za-z_]+)$");
  25.         Matcher matcherEndKeyString = regexEndKeyString.matcher(keyString);
  26.  
  27.         if (matcherEndKeyString.find()) {
  28.             endKey = matcherEndKeyString.group(1);
  29.         } else {
  30.             System.out.println("<p>A key is missing</p>");
  31.             return;
  32.         }
  33.  
  34.         String regexTextStringPattern = startKey + "([0-9.]+?)" + endKey;
  35.         Pattern regexTextString = Pattern.compile(regexTextStringPattern);
  36.         Matcher matcherTextString = regexTextString.matcher(textString);
  37.  
  38.         String value = "";
  39.         double sum = 0.0;
  40.         int countDoubleValues = 0;
  41.  
  42.         while (matcherTextString.find()) {
  43.  
  44.             sum += Double.parseDouble(matcherTextString.group(1));
  45.             if (matcherTextString.group().contains(".")) {
  46.                 countDoubleValues++;
  47.             }
  48.         }
  49.  
  50.         if (sum > 0 && countDoubleValues > 0) {
  51.             System.out.printf("<p>The total value is: <em>%.2f</em></p>", sum);
  52.         } else if (sum > 0 && countDoubleValues == 0) {
  53.             System.out.printf("<p>The total value is: <em>%d</em></p>", (int) sum);
  54.         } else if (sum == 0) {
  55.             System.out.printf("<p>The total value is: <em>nothing</em></p>");
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement