Advertisement
desislava_topuzakova

02. Ad Astra

Nov 24th, 2023
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. package examPreparation;
  2.  
  3. import java.util.Scanner;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6.  
  7. public class SecondTask {
  8. public static void main(String[] args) {
  9. Scanner scanner = new Scanner(System.in);
  10. String text = scanner.nextLine(); //текст с информация
  11. //text = "#Bread#19/03/21#4000#|Invalid|03/03.20||Apples|08/10/20|200||Carrots|06/08/20|500||Not right|6.8.20|5|"
  12. String regex = "([#|])(?<foodName>[A-Za-z\\s]+)\\1(?<expirationDate>[0-9]{2}\\/[0-9]{2}\\/[0-9]{2})\\1(?<calories>[0-9]{1,5})\\1";
  13. Pattern pattern = Pattern.compile(regex); //шаблон
  14. Matcher matcher = pattern.matcher(text);
  15. //matcher = {"#Bread#19/03/21#4000#", "|Apples|08/10/20|200|", "|Carrots|06/08/20|500|"}
  16.  
  17. int totalCalories = 0; //сума от калориите на храни
  18. StringBuilder foodsOutput = new StringBuilder(); //конструирам храните за отпечатване
  19.  
  20. while (matcher.find()) {
  21. //matcher -> "#Bread#19/03/21#4000#"
  22. //matcher = "#(?<foodName>Bread)#(?<expirationDate>19/03/21)#(?<calories>4000)#";
  23. String foodName = matcher.group("foodName"); //"Bread"
  24. String expirationDate = matcher.group("expirationDate"); //"19/03/21"
  25. int calories = Integer.parseInt(matcher.group("calories")); //"4000" -> 4000
  26.  
  27. totalCalories += calories;
  28. String output = String.format("Item: %s, Best before: %s, Nutrition: %d%n", foodName, expirationDate, calories);
  29. foodsOutput.append(output);
  30. }
  31.  
  32. //знаем колко общо калории може да си набавим от храната
  33. int days = totalCalories / 2000; //колко дни ще оцелеем с наличната храна
  34. System.out.printf("You have food to last you for: %d days!%n", days);
  35. //отпечатваме храните
  36. System.out.println(foodsOutput);
  37.  
  38.  
  39.  
  40. }
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement