Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package StringAndTextProcessing.Exercises;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class SumAllValues {
- public static void main(String[] args) throws IOException {
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
- String keys = reader.readLine();
- String text = reader.readLine();
- String startKey = "\\b([A-Za-z_]+)(\\d+)"; // group 1 is the key
- String endKey = "(\\d+)([A-Za-z_]+)\\b"; //group 2 is the key
- Pattern start = Pattern.compile(startKey);
- Pattern end = Pattern.compile(endKey);
- Matcher startMatch = start.matcher(keys);
- Matcher endMatch = end.matcher(keys);
- String startS = "";
- String endS = "";
- if (startMatch.find()) {
- startS = startMatch.group(1);
- }
- if (endMatch.find()) {
- endS = endMatch.group(2);
- }
- String findNumbers = "(\\d+\\.?\\d+)";
- Pattern number = Pattern.compile(startS + findNumbers + endS);
- double sum = 0;
- Matcher numbers = number.matcher(text);
- while (numbers.find()) {
- sum += Double.parseDouble(numbers.group(1));
- }
- int sumInt = 0;
- if (endS.isEmpty() || startS.isEmpty()) {
- System.out.println("<p>A key is missing</p>");
- return;
- }
- if (sum == 0) {
- System.out.println("<p>The total value is: <em>nothing</em></p>");
- } else if ((int)sum == sum){
- System.out.printf("<p>The total value is: <em>%d</em></p>", (int)sum);
- }
- else {
- System.out.printf("<p>The total value is: <em>%.2f</em></p>", sum);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement