myrdok123

Untitled

Jul 29th, 2024
362
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.23 KB | None | 0 0
  1. package Exam_Prep;
  2.  
  3. import java.util.*;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6.  
  7. public class P02_AdAstra {
  8.     public static void main(String[] args) {
  9.         Scanner scanner = new Scanner(System.in);
  10.  
  11.         String regex = "(?<delimiter>[#?\\|?])(?<product>[A-Z a-z]+)\\1(?<date>[0-9]{2}\\/[0-9]{2}\\/[0-9]{2})\\1(?<calories>[0-9]+)\\1";
  12.  
  13.         String input = scanner.nextLine();
  14.  
  15.         Pattern pattern = Pattern.compile(regex);
  16.         Matcher matcher = pattern.matcher(input);
  17.  
  18.         List<String> products = new ArrayList<>();
  19.  
  20.         int caloriesSum = 0;
  21.  
  22.        while (matcher.find()) {
  23.  
  24.            String currentProduct = matcher.group("product");
  25.            String currentDate = matcher.group("date");
  26.            String currentCalories = matcher.group("calories");
  27.            products.add(String.format("Item: %s, Best before: %s, Nutrition: %s",
  28.                    currentProduct, currentDate, currentCalories));
  29.  
  30.            caloriesSum += Integer.parseInt(currentCalories);
  31.  
  32.        }
  33.  
  34.        int actualDays = caloriesSum/2000;
  35.  
  36.  
  37.         System.out.printf("You have food to last you for: %d days!%n", actualDays);
  38.         products.forEach(System.out::println);
  39.  
  40.  
  41.  
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment