Advertisement
Guest User

Untitled

a guest
May 9th, 2018
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 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 Pr14SumOfAllValues {
  6.  
  7.     public static void main(String[] args) {
  8.  
  9.         Scanner scanner = new Scanner(System.in);
  10.  
  11.         String keyString = scanner.nextLine();
  12.         String text = scanner.nextLine();
  13.  
  14.         String keysRegex = "(?<=^)([A-Za-z_]+)(?=\\d).*(?<=\\d)([A-Za-z_]+)(?=$)";
  15.         Matcher keysMatcher = Pattern.compile(keysRegex).matcher(keyString);
  16.  
  17.         if (!keysMatcher.find()) {
  18.             System.out.println("<p>A key is missing</p>");
  19.         } else {
  20.             String startKey = keysMatcher.group(1);
  21.             String endKey = keysMatcher.group(2);
  22.  
  23.             String regex = Pattern.quote(startKey) + "(\\d*(?:\\.\\d+)?)" + Pattern.quote(endKey);
  24.             Matcher matcher = Pattern.compile(regex).matcher(text);
  25.  
  26.             double sum = 0d;
  27.             while (matcher.find() && !matcher.group(1).isEmpty()) {
  28.                 sum += Double.parseDouble(matcher.group(1));
  29.             }
  30.  
  31.             if (sum != 0d) {
  32.                 if (sum == (int) sum) {
  33.                     System.out.printf("<p>The total value is: <em>%d</em></p>", (int) sum);
  34.                 } else {
  35.                     System.out.printf("<p>The total value is: <em>%.2f</em></p>%n", sum);
  36.                 }
  37.             } else {
  38.                 System.out.println("<p>The total value is: <em>nothing</em></p>");
  39.             }
  40.         }
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement