Advertisement
IrinaIgnatova

RegEx - Furniture

Jul 24th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.00 KB | None | 0 0
  1. package com.company;
  2.  
  3.  
  4. import java.util.*;
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7. import java.util.stream.Collectors;
  8.  
  9. public class Main {
  10.  
  11.     public static void main(String[] args) {
  12.  
  13.         Scanner scanner = new Scanner(System.in);
  14.         String input = scanner.nextLine();
  15.         String regex = ">>(?<furniture>[A-Z]*[a-z]*)<<(?<price>\\d+[.]{0,1}[\\d]*)!(?<quantity>\\d{1,9})+";//може и без имена, само по                
  16.                                                                                                              групи
  17.         // String regex = ">>(?<furniture>[A-Za-z]+)<<(?<price>[0-9]+\\.?[0-9]+)!(?<quantity>\\d+)";//други верни варианти
  18.         // String regex = ">>(?<furniture>\W+)<<(?<price>\d+\\.?\d+)!(?<quantity>\\d+)";
  19.        
  20. Pattern pattern = Pattern.compile(regex);
  21.         List<String> furnitureName = new ArrayList<>();
  22.  
  23.         double totalSpentMoney = 0;
  24.  
  25.         while (!input.equals("Purchase")) {
  26.            
  27.             Matcher matcher = pattern.matcher(input);
  28.  
  29.             while (matcher.find()) {
  30.                 String furniture = matcher.group("furniture");//може и без да именуваме само с номер на група да печатаме
  31.                 double price = Double.parseDouble(matcher.group("price"));
  32.                 int quantity = Integer.parseInt(matcher.group("quantity"));
  33.                 double spentMoney = price * quantity;
  34.                 totalSpentMoney += spentMoney;
  35.  
  36.                 furnitureName.add(furniture);
  37.  
  38.             }
  39.  
  40.             input = scanner.nextLine();
  41.         }
  42.  
  43.         //System.out.printf("Bought furniture:%n");  ГРЕШНО
  44.        // System.out.println(String.join("\n", furnitureName)); ГРЕШНО
  45.        
  46.         System.out.println("Bought furniture:");
  47.         for (String name : furnitureName) {
  48.             System.out.println(name);
  49.         }
  50.  
  51.         System.out.printf("Total money spend: %.2f", totalSpentMoney);
  52.  
  53.     }
  54.  
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement