Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class FeedTheAnimal {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- Map<String, Integer> animalAndFood = new LinkedHashMap<>();
- Map<String, Integer> areaAndCount = new LinkedHashMap<>();
- String input = scanner.nextLine();
- while (!input.equals("Last Info")) {
- String[] text = input.split(":");
- String command = text[0];
- String name = text[1];
- int food = Integer.parseInt(text[2]);
- String area = text[3];
- if (command.equals("Add")) {
- if (!animalAndFood.containsKey(name)) {
- animalAndFood.put(name, food);
- if (!areaAndCount.containsKey(area)) {
- areaAndCount.put(area, 1);
- } else {
- int currNum = areaAndCount.get(area);
- areaAndCount.put(area, currNum + 1);
- }
- } else {
- int currFood = animalAndFood.get(name);
- animalAndFood.put(name, currFood + food);
- }
- } else if (command.equals("Feed")) {
- if (animalAndFood.containsKey(name)) {
- int newFood = animalAndFood.get(name) - food;
- animalAndFood.put(name, newFood);
- if (newFood <= 0) {
- System.out.printf("%s was successfully fed%n", name);
- animalAndFood.remove(name);
- int currNum = areaAndCount.get(area);
- if (currNum > 1) {
- areaAndCount.put(area, currNum - 1);
- } else {
- areaAndCount.remove(area);
- }
- }
- }
- }
- input = scanner.nextLine();
- }
- System.out.println("Animals:");
- animalAndFood.entrySet().stream().sorted((a, b) ->{
- int sort = b.getValue().compareTo(a.getValue());
- if(sort == 0){
- sort = a.getKey().compareTo(b.getKey());
- }
- return sort;
- }).forEach(entry -> System.out.printf("%s -> %dg%n", entry.getKey(), entry.getValue()));
- System.out.println("Areas with hungry animals:");
- areaAndCount.entrySet().stream().sorted((a1, a2) -> a2.getValue().compareTo(a1.getValue())
- ).forEach(entry -> System.out.printf("%s : %d%n", entry.getKey(), entry.getValue()));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement