Advertisement
valkata

SumOfAllValues

Sep 30th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 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 sumOfAllValues {
  6.     public static void main(String[] args) {
  7.         Scanner input = new Scanner(System.in);
  8.         String keyPattern = "^([A-Za-z_]+)(?=[0-9])[0-9]+.*(?<=[0-9])([A-Za-z_]+)";
  9.         String keyInput = input.nextLine();
  10.         String textInput = input.nextLine();
  11.         double sum = 0.0;
  12.         Pattern keyRegEx = Pattern.compile(keyPattern);
  13.         Matcher keyMatcher = keyRegEx.matcher(keyInput);
  14.  
  15.         if (keyMatcher.find()) {
  16.             String startKey = keyMatcher.group(1);
  17.             String endKey = keyMatcher.group(2);
  18.  
  19.             String numberPattern = "^([0-9]+\\.?[0-9]*)$";
  20.             Pattern numberRegEx = Pattern.compile(numberPattern);
  21.             while (true) {
  22.                 int index1 = textInput.indexOf(startKey);
  23.                 int index2 = textInput.indexOf(endKey,index1+startKey.length());
  24.  
  25.                 if(index1 == -1 || index2 == -1){
  26.                     break;
  27.                 }
  28.                 String num = textInput.substring(index1 + startKey.length(), index2);
  29.                 Matcher numberMatcher = numberRegEx.matcher(num);
  30.  
  31.                 if (numberMatcher.find()) {
  32.                     sum += Double.parseDouble(numberMatcher.group());
  33.                 }
  34.                 String replaceString = textInput.substring(index1, index2 + endKey.length());
  35.                 textInput = textInput.replace(replaceString, "");
  36.  
  37.             }
  38.         } else {
  39.             System.out.println("<p>A key is missing</p>");
  40.             return;
  41.         }
  42.  
  43.         if (sum == 0.0) {
  44.             System.out.println("<p>The total value is: <em>nothing</em></p>");
  45.         }
  46.         else{
  47.             System.out.printf("<p>The total value is: <em>%.2f</em></p>",sum);
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement