Advertisement
Krassi_Daskalova

Feed The Animals

Aug 2nd, 2019
738
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class FeedTheAnimal {
  4. public static void main(String[] args) {
  5. Scanner scanner = new Scanner(System.in);
  6.  
  7. Map<String, Integer> animalAndFood = new LinkedHashMap<>();
  8. Map<String, Integer> areaAndCount = new LinkedHashMap<>();
  9.  
  10. String input = scanner.nextLine();
  11. while (!input.equals("Last Info")) {
  12. String[] text = input.split(":");
  13. String command = text[0];
  14. String name = text[1];
  15. int food = Integer.parseInt(text[2]);
  16. String area = text[3];
  17.  
  18. if (command.equals("Add")) {
  19. if (!animalAndFood.containsKey(name)) {
  20. animalAndFood.put(name, food);
  21. if (!areaAndCount.containsKey(area)) {
  22. areaAndCount.put(area, 1);
  23. } else {
  24. int currNum = areaAndCount.get(area);
  25. areaAndCount.put(area, currNum + 1);
  26. }
  27. } else {
  28. int currFood = animalAndFood.get(name);
  29. animalAndFood.put(name, currFood + food);
  30. }
  31. } else if (command.equals("Feed")) {
  32. if (animalAndFood.containsKey(name)) {
  33. int newFood = animalAndFood.get(name) - food;
  34. animalAndFood.put(name, newFood);
  35. if (newFood <= 0) {
  36. System.out.printf("%s was successfully fed%n", name);
  37. animalAndFood.remove(name);
  38. int currNum = areaAndCount.get(area);
  39. if (currNum > 1) {
  40. areaAndCount.put(area, currNum - 1);
  41. } else {
  42. areaAndCount.remove(area);
  43. }
  44. }
  45. }
  46. }
  47. input = scanner.nextLine();
  48. }
  49. System.out.println("Animals:");
  50. animalAndFood.entrySet().stream().sorted((a, b) ->{
  51. int sort = b.getValue().compareTo(a.getValue());
  52. if(sort == 0){
  53. sort = a.getKey().compareTo(b.getKey());
  54. }
  55. return sort;
  56. }).forEach(entry -> System.out.printf("%s -> %dg%n", entry.getKey(), entry.getValue()));
  57. System.out.println("Areas with hungry animals:");
  58. areaAndCount.entrySet().stream().sorted((a1, a2) -> a2.getValue().compareTo(a1.getValue())
  59. ).forEach(entry -> System.out.printf("%s : %d%n", entry.getKey(), entry.getValue()));
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement