A_Marinov

Untitled

Dec 11th, 2020
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | None | 0 0
  1. package FinalExamAugustRetake;
  2.  
  3. import java.util.LinkedHashMap;
  4. import java.util.Map;
  5. import java.util.Scanner;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8.  
  9. public class AdAstra_02 {
  10.     public static void main(String[] args) {
  11.         Scanner scan = new Scanner(System.in);
  12.  
  13.         final String REGEX = "([#\\|])(?<name>[A-Za-z\\s]+)\\1(?<date>\\d{2}\\/\\d{2}\\/\\d{2})*\\1(?<calories>\\d{1,5})\\1";
  14.  
  15.         Map<String[], Integer> data = new LinkedHashMap<>();
  16.  
  17.         String input = scan.nextLine();
  18.  
  19.         Pattern pattern = Pattern.compile(REGEX);
  20.         Matcher matcher = pattern.matcher(input);
  21.         int totalCals = 0;
  22.  
  23.         while (matcher.find()) {
  24.             String name = matcher.group("name");
  25.             String date = matcher.group("date");
  26.             int cals = Integer.parseInt(matcher.group("calories"));
  27.  
  28.             String[] info = new String[]{name, date};
  29.             data.putIfAbsent(info, cals);
  30.             totalCals += cals;
  31.         }
  32.         int totalDays = totalCals / 2000;
  33.         System.out.printf("You have food to last you for: %d days!%n", totalDays);
  34.  
  35.         for (var entry : data.entrySet()) {
  36.             System.out.println(String.format("Item: %s, Best before: %s, Nutrition: %d"
  37.                     ,entry.getKey()[0],entry.getKey()[1],entry.getValue()));
  38.         }
  39.     }
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment