Advertisement
desislava_topuzakova

02. Ad Astra

Nov 25th, 2022
467
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. package exam_preparation;
  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.  
  11. String text = scanner.nextLine(); //текст с информация
  12. //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|"
  13. String regex = "(#|\\|)(?<foodName>[A-Za-z\\s]+)\\1(?<expirationDate>[0-9]{2}\\/[0-9]{2}\\/[0-9]{2})\\1(?<calories>[0-9]+)\\1";
  14. Pattern pattern = Pattern.compile(regex); //шаблон
  15. Matcher matcher = pattern.matcher(text);
  16. //matcher = {"#Bread#19/03/21#4000#", "|Apples|08/10/20|200|", "|Carrots|06/08/20|500|"}
  17.  
  18. int totalCalories = 0; //сума от калориите на храните
  19.  
  20. StringBuilder outputItems = new StringBuilder();
  21.  
  22. while (matcher.find()) {
  23. //found = "#Bread#19/03/21#4000#"
  24. //"#(?<foodName>Bread)#(?<expirationDate>19/03/21)#(?<calories>4000)#"
  25. String foodName = matcher.group("foodName"); //"Bread"
  26. String expDate = matcher.group("expirationDate"); //"19/03/21"
  27. int calories = Integer.parseInt(matcher.group("calories")); //"4000" -> 4000
  28.  
  29. totalCalories += calories;
  30. outputItems.append(String.format("Item: %s, Best before: %s, Nutrition: %d%n", foodName, expDate, calories));
  31. }
  32.  
  33. int days = totalCalories / 2000; //брой дни, в които ядем по 2000 калории
  34. System.out.printf("You have food to last you for: %d days!%n", days);
  35. System.out.println(outputItems);
  36.  
  37.  
  38. }
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement