Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * You are given a keys string and a text string.
- * Write a program that finds the start key and the end key from the keys string and then applies them to the text string.
- * The start key will always stay at the beginning of the keys string.
- * It can contain only letters and underscore and ends just before the first found digit.
- * The end key will always stay at the end of the keys string.
- * It can contain only letters and underscore and starts just after the last found digit.
- * Print at the console the sum of all values (only integer and floating-point numbers with dot as a separator are considered valid)
- * in the text string, between a start key and an end key. If the value is 0 then print “The total value is: nothing”.
- * If no start key or no end key is found, then print “A key is missing”.
- * The Input will be read from the console.
- * The first line will hold the keys string and the second line will hold the text to search.
- * The output should hold the result text, printed in an HTML paragraph. The actual value of the sum should be italic.
- * The number should been 2 digits rounded after decimal separator.
- */
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Locale;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class SumOfAllValues {
- public static void main(String[] args) {
- Locale.setDefault(Locale.ROOT);
- String keysStr = "";
- String text = "";
- try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
- keysStr = reader.readLine();
- text = reader.readLine();
- } catch (IOException e) {
- e.printStackTrace();
- }
- Pattern keysPattern = Pattern.compile("^([a-zA-Z_]+)\\d.*\\d([a-zA-Z_]+)");
- Matcher keysMatcher = keysPattern.matcher(keysStr);
- if (!keysMatcher.find()) {
- System.out.println("<p>A key is missing</p>");
- return;
- }
- String startKey = keysMatcher.group(1);
- String endKey = keysMatcher.group(2);
- Pattern valuesPattern = Pattern
- .compile(Pattern.quote(startKey) + "([\\d.]+)" + Pattern.quote(endKey));
- Matcher valuesMatcher = valuesPattern.matcher(text);
- double valuesSum = 0;
- while (valuesMatcher.find()) {
- valuesSum += Double.parseDouble(valuesMatcher.group(1));
- }
- if (valuesSum != 0) {
- if (valuesSum == (int) valuesSum) {
- System.out.printf("<p>The total value is: <em>%d</em></p>", (int) valuesSum);
- } else {
- System.out.printf("<p>The total value is: <em>%.2f</em></p>", valuesSum);
- }
- } else {
- System.out.println("<p>The total value is: <em>nothing</em></p>");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement