desislava_topuzakova

01. Furniture

Nov 19th, 2021
1,346
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | None | 0 0
  1. package Regex_Exercise;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.Scanner;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8.  
  9. public class Furniture_01 {
  10.     public static void main(String[] args) {
  11.         Scanner scanner = new Scanner(System.in);
  12.         String input = scanner.nextLine();
  13.         List<String> furniture = new ArrayList<>(); //имената на мебелите
  14.         double totalSum = 0; //обща изхарчена сума
  15.  
  16.         //">>{furniture name}<<{price}!{quantity}"
  17.         //String regex = ">>(?<furnitureName>[A-Za-z]+)<<(?<price>[0-9]+.?[0-9]*)!(?<quantity>[0-9]+)";
  18.         String regex = ">>(?<furnitureName>\\w+)<<(?<price>\\d+.?\\d*)!(?<quantity>\\d+)";
  19.         Pattern pattern = Pattern.compile(regex);
  20.         while(!input.equals("Purchase")) {
  21.             //">>Sofa<<312.23!3"
  22.             Matcher matcher = pattern.matcher(input);
  23.             if (matcher.find()) {
  24.                 //true -> input отговаря на regex-a в pattern-a
  25.                 //false -> input НЕ отговаря на regex-a в pattern-a
  26.                 String furnitureName = matcher.group("furnitureName");
  27.                 double price = Double.parseDouble(matcher.group("price"));
  28.                 int quantity = Integer.parseInt(matcher.group("quantity"));
  29.  
  30.                 furniture.add(furnitureName);
  31.                 totalSum += price * quantity;
  32.             }
  33.             input = scanner.nextLine();
  34.         }
  35.  
  36.         System.out.println("Bought furniture:");
  37.         furniture.forEach(System.out::println);
  38.         System.out.printf("Total money spend: %.2f", totalSum);
  39.     }
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment