desislava_topuzakova

Untitled

Nov 27th, 2021
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.03 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. Scanner scan = new Scanner(System.in);
  6. Map<String, Plant> plants = new HashMap<>();
  7.  
  8. int n = Integer.parseInt(scan.nextLine());
  9. for (int i = 0; i < n; i++) {
  10. String[] tokens = scan.nextLine().split("<->");
  11. String plant = tokens[0];
  12. int rarity = Integer.parseInt(tokens[1]);
  13.  
  14. plants.putIfAbsent(plant, new Plant());
  15. plants.get(plant).setRarity(rarity);
  16. }
  17.  
  18. String input = scan.nextLine();
  19. while (!"Exhibition".equals(input)) {
  20. String[] tokens = input.split(": | - ");
  21. String command = tokens[0];
  22. String plant = tokens[1];
  23.  
  24. if (!plants.containsKey(plant)) {
  25. input = scan.nextLine();
  26. System.out.println("error");
  27. continue;
  28. }
  29.  
  30. switch (command) {
  31. case "Rate":
  32. int rating = Integer.parseInt(tokens[2]);
  33. plants.get(plant).addRating(rating);
  34. break;
  35. case "Update":
  36. int rarity = Integer.parseInt(tokens[2]);
  37. plants.get(plant).setRarity(rarity);
  38. break;
  39. case "Reset":
  40. plants.get(plant).removeAllRating();
  41. break;
  42. }
  43. input = scan.nextLine();
  44. }
  45.  
  46. System.out.println("Plants for the exhibition:");
  47.  
  48. plants
  49. .entrySet()
  50. .stream()
  51. .sorted((p1, p2) -> {
  52. int result = Integer.compare(p2.getValue().getRarity(), p1.getValue().getRarity());
  53. if (result == 0) {
  54. result = Double.compare(p2.getValue().getAverageRating(), p1.getValue().getAverageRating());
  55. }
  56. return result;
  57. })
  58. .forEach(p -> System.out.printf("- %s; Rarity: %s; Rating: %.2f%n",
  59. p.getKey(),
  60. p.getValue().getRarity(),
  61. p.getValue().getAverageRating()));
  62. }
  63.  
  64. static class Plant {
  65. private int rarity;
  66. private List<Integer> ratings;
  67.  
  68. public Plant() {
  69. this.ratings = new ArrayList<>();
  70. }
  71.  
  72. public int getRarity() {
  73. return rarity;
  74. }
  75.  
  76. public void setRarity(int rarity) {
  77. this.rarity = rarity;
  78. }
  79.  
  80. public void addRating(int rating) {
  81. this.ratings.add(rating);
  82. }
  83.  
  84. public void removeAllRating() {
  85. this.ratings.clear();
  86. }
  87.  
  88. public double getAverageRating() {
  89. double avg = 0.0;
  90. for (Integer rating : this.ratings) {
  91. avg += rating;
  92. }
  93. return this.ratings.size() > 0 ? avg / this.ratings.size() : 0;
  94. }
  95. }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment