Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class sumOfAllValues {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- String keyPattern = "^([A-Za-z_]+)(?=[0-9])[0-9]+.*(?<=[0-9])([A-Za-z_]+)";
- String keyInput = input.nextLine();
- String textInput = input.nextLine();
- double sum = 0.0;
- Pattern keyRegEx = Pattern.compile(keyPattern);
- Matcher keyMatcher = keyRegEx.matcher(keyInput);
- if (keyMatcher.find()) {
- String startKey = keyMatcher.group(1);
- String endKey = keyMatcher.group(2);
- String numberPattern = "^([0-9]+\\.?[0-9]*)$";
- Pattern numberRegEx = Pattern.compile(numberPattern);
- while (true) {
- int index1 = textInput.indexOf(startKey);
- int index2 = textInput.indexOf(endKey,index1+startKey.length());
- if(index1 == -1 || index2 == -1){
- break;
- }
- String num = textInput.substring(index1 + startKey.length(), index2);
- Matcher numberMatcher = numberRegEx.matcher(num);
- if (numberMatcher.find()) {
- sum += Double.parseDouble(numberMatcher.group());
- }
- String replaceString = textInput.substring(index1, index2 + endKey.length());
- textInput = textInput.replace(replaceString, "");
- }
- } else {
- System.out.println("<p>A key is missing</p>");
- return;
- }
- if (sum == 0.0) {
- System.out.println("<p>The total value is: <em>nothing</em></p>");
- }
- else{
- System.out.printf("<p>The total value is: <em>%.2f</em></p>",sum);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement