Advertisement
CR7CR7

Ad Astra -HasMap

Aug 18th, 2023
1,529
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. import java.util.HashMap;
  5.  
  6. public class Main {
  7.     public static void main(String[] args) {
  8.         Scanner scanner = new Scanner(System.in);
  9.         String inputStr = scanner.nextLine();
  10.         String regex = "(?<index>[\\\\|\\\\#]{1})(?<item>[A-z\\s+]+)\\1(?<date>[0-9]{2}[\\/]{1}[0-9]{2}[\\/]{1}[0-9]{2})\\1(?<calories>\\d{1,5})\\1";
  11.         Pattern pattern = Pattern.compile(regex);
  12.  
  13.         int days = 0;
  14.         HashMap<String, Integer> foodCalories = new HashMap<String, Integer>();
  15.         Matcher matcher = pattern.matcher(inputStr);
  16.         while (matcher.find()) {
  17.             String item = matcher.group("item");
  18.             int current = Integer.parseInt(matcher.group("calories"));
  19.             foodCalories.put(item, current);
  20.             days += current;
  21.         }
  22.  
  23.         System.out.println("You have food to last you for: " + (days / 2000) + " days!");
  24.  
  25.         matcher = pattern.matcher(inputStr);
  26.         while (matcher.find()) {
  27.             String item = matcher.group("item");
  28.             String date = matcher.group("date");
  29.             int calories = Integer.parseInt(matcher.group("calories"));
  30.             System.out.println("Item: " + item + ", Best before: " + date + ", Nutrition: " + calories);
  31.         }
  32.     }
  33. }
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement