SPDG57

Furniture - Regex [Named capture groups]

Nov 24th, 2019
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.47 KB | None | 0 0
  1. package com.company;
  2.  
  3. import javafx.util.Pair;
  4.  
  5. import javax.xml.crypto.dsig.keyinfo.KeyValue;
  6. import java.security.KeyStore;
  7. import java.text.Collator;
  8. import java.text.DecimalFormat;
  9. import java.util.*;
  10. import java.util.function.Predicate;
  11. import java.util.regex.Matcher;
  12. import java.util.regex.Pattern;
  13. import java.util.stream.Collector;
  14. import java.util.stream.Collectors;
  15.  
  16.  
  17. public class Main {
  18.     public static void main(String[] args) {
  19.         Scanner scanner = new Scanner(System.in);
  20.  
  21.         String regex = ">>(?<furniture>[A-Za-z]+)<<(?<price>\\d+.?\\d+)!(?<quantity>\\d+)";
  22.         Pattern pattern = Pattern.compile(regex);
  23.  
  24.         List<String> boughtFurniture = new ArrayList<>();
  25.         Double total = 0.0;
  26.  
  27.         String input;
  28.         while (!"Purchase".equals(input = scanner.nextLine())){
  29.             Matcher purchases = pattern.matcher(input);
  30.  
  31.             if(purchases.find()) {
  32.                 String furniture = purchases.group("furniture");
  33.                 double price = Double.parseDouble(purchases.group("price"));
  34.                 int quantity = Integer.parseInt(purchases.group("quantity"));
  35.  
  36.                 boughtFurniture.add(furniture);
  37.                 total += price * quantity;
  38.             }
  39.         }
  40.  
  41.         System.out.println("Bought furniture:");
  42.         for (String furniture : boughtFurniture){
  43.             System.out.println(furniture);
  44.         }
  45.  
  46.         System.out.printf("Total money spend: %.2f", total);
  47.     }
  48. }
Add Comment
Please, Sign In to add comment