Advertisement
emodev

SumAllValues

Jan 10th, 2019
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.84 KB | None | 0 0
  1. package StringAndTextProcessing.Exercises;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8.  
  9. public class SumAllValues {
  10.     public static void main(String[] args) throws IOException {
  11.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  12.  
  13.         String keys = reader.readLine();
  14.         String text = reader.readLine();
  15.  
  16.         String startKey = "\\b([A-Za-z_]+)(\\d+)"; // group 1 is the key
  17.         String endKey = "(\\d+)([A-Za-z_]+)\\b"; //group 2 is the key
  18.  
  19.         Pattern start = Pattern.compile(startKey);
  20.         Pattern end = Pattern.compile(endKey);
  21.  
  22.         Matcher startMatch = start.matcher(keys);
  23.         Matcher endMatch = end.matcher(keys);
  24.  
  25.         String startS = "";
  26.         String endS = "";
  27.  
  28.         if (startMatch.find()) {
  29.             startS = startMatch.group(1);
  30.         }
  31.         if (endMatch.find()) {
  32.             endS = endMatch.group(2);
  33.         }
  34.  
  35.         String findNumbers = "(\\d+\\.?\\d+)";
  36.         Pattern number = Pattern.compile(startS + findNumbers + endS);
  37.  
  38.         double sum = 0;
  39.         Matcher numbers = number.matcher(text);
  40.         while (numbers.find()) {
  41.             sum += Double.parseDouble(numbers.group(1));
  42.         }
  43.  
  44.         int sumInt = 0;
  45.  
  46.         if (endS.isEmpty() || startS.isEmpty()) {
  47.             System.out.println("<p>A key is missing</p>");
  48.             return;
  49.         }
  50.         if (sum == 0) {
  51.             System.out.println("<p>The total value is: <em>nothing</em></p>");
  52.         } else if ((int)sum == sum){
  53.             System.out.printf("<p>The total value is: <em>%d</em></p>", (int)sum);
  54.         }
  55.         else {
  56.             System.out.printf("<p>The total value is: <em>%.2f</em></p>", sum);
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement