Advertisement
desislava_topuzakova

01. Furniture

Nov 20th, 2022
878
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. package regex;
  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.         List<String> furnitureNames = new ArrayList<>(); //имената на мебелите
  13.         double totalSum = 0 ; //общо изхарчена сума за всички въведени мебели
  14.  
  15.         String regex = ">>(?<furniture>[A-Za-z]+)<<(?<price>[0-9]+\\.?[0-9]*)!(?<quantity>[0-9]+)";
  16.         Pattern pattern = Pattern.compile(regex); //шаблон
  17.  
  18.         String input = scanner.nextLine();
  19.         while(!input.equals("Purchase")) {
  20.             //input = ">>Sofa<<312.23!3"
  21.             Matcher matcher = pattern.matcher(input);
  22.             //matcher = ">>(?<furniture>Sofa)<<(?<price>312.23)!(?<quantity>3)"
  23.  
  24.             //true -> input отговарят на шаблона
  25.             //false -> input не отговаря на шаблона
  26.             if (matcher.find()) {
  27.                 String furnitureName = matcher.group("furniture"); //"Sofa"
  28.                 double price = Double.parseDouble(matcher.group("price")); //"312.23" -> parse -> 312.23
  29.                 int quantity = Integer.parseInt(matcher.group("quantity")); //"3" -> parse -> 3
  30.  
  31.                 furnitureNames.add(furnitureName);
  32.                 double currentFurniturePrice = price * quantity; //платено за текущата мебел
  33.                 totalSum += currentFurniturePrice;
  34.             }
  35.             input = scanner.nextLine();
  36.         }
  37.  
  38.         System.out.println("Bought furniture:");
  39.         furnitureNames.forEach(System.out::println);
  40.         System.out.printf("Total money spend: %.2f", totalSum);
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement