Didart

Ad Astra

Oct 21st, 2021
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.56 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4.  
  5. public class AdAstra {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.         String stringLine = scanner.nextLine();
  10.        
  11.         String regex = "(?<symbols>[#\\|])(?<name>[A-za-z\\s]+)(\\1)(?<date>[0-9]{2}[\\/][0-9]{2}[\\/][0-9]{2})(\\1)(?<calories>[\\d]{1,5})(\\1)";
  12.         Pattern pattern = Pattern.compile(regex);
  13.         Matcher matcher = pattern.matcher(stringLine);
  14.         Map<String, String> foodDate = new LinkedHashMap<>();
  15.         Map<String, Integer> foodCalories = new LinkedHashMap<>();
  16.         List<String> items = new LinkedList<>();
  17.        
  18.         int totalCalories = 0;    
  19.         while (matcher.find()) {
  20.             String nameofItem = matcher.group("name");
  21.             String expirationDate = matcher.group("date");
  22.             int calories = Integer.parseInt(matcher.group("calories"));
  23.  
  24.             foodDate.putIfAbsent(nameofItem, expirationDate);
  25.             foodCalories.putIfAbsent(nameofItem, calories);
  26.             totalCalories += calories;  //change
  27.             items.add(String.format("Item: %s, Best before: %s, Nutrition: %d%n", nameofItem, expirationDate, calories));
  28.         }
  29.  
  30.         int sum = 0;
  31.         for (Map.Entry<String, Integer> entry : foodCalories.entrySet()) {
  32.             sum += entry.getValue();
  33.         }
  34.  
  35.         System.out.printf("You have food to last you for: %d days!%n", totalCalories / 2000);
  36.         items.forEach(System.out::print);
  37.  
  38.     }
  39.        
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment