Advertisement
Guest User

Untitled

a guest
Mar 27th, 2020
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.99 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class ex3 {
  4. public static void main(String[] args) {
  5. Scanner scanner = new Scanner( System.in );
  6. String input = scanner.nextLine();
  7. Map<String, List<String>> heroes = new HashMap<>();
  8. while (!"End".equals( input )) {
  9. String[] tokens = input.split( " " );
  10. String command = tokens[0];
  11. String heroName = tokens[1];
  12. switch (command) {
  13. case "Enroll": {
  14. if (!heroExists( heroName, heroes )) {
  15. heroes.put( heroName, new ArrayList<>() );
  16. } else {
  17. System.out.println( String.format( "%s is already enrolled.", heroName ) );
  18. }
  19. break;
  20. }
  21. case "Learn": {
  22. String spell = tokens[2];
  23. if (heroExists( heroName, heroes )) {
  24. if (heroes.get( heroName ).contains( spell )) {
  25. System.out.println( String.format( "%s has already learnt %s.", heroName, spell ) );
  26. } else {
  27. heroes.get( heroName ).add( spell );
  28. }
  29. } else {
  30. System.out.println( String.format( "%s doesn't exist.", heroName ) );
  31. }
  32. break;
  33. }
  34. case "Unlearn": {
  35. String spell = tokens[2];
  36. if (heroExists( heroName, heroes )) {
  37. if (heroes.get( heroName ).contains( spell )) {
  38. heroes.get( heroName ).remove( spell );
  39. } else {
  40. System.out.println( String.format( "%s doesn't know %s.", heroName, spell ) );
  41.  
  42. }
  43. } else {
  44. System.out.println( String.format( "%s doesn't exist.", heroName ) );
  45. }
  46. break;
  47. }
  48. }
  49.  
  50. input = scanner.nextLine();
  51. }
  52. System.out.println( "Heroes:" );
  53. heroes.entrySet().stream()
  54. .sorted( (a, b) ->
  55. {
  56. int sizeA = a.getValue().size();
  57. int sizeB = b.getValue().size();
  58. String nameA=a.getKey();
  59. String nameB=b.getKey();
  60. if (sizeA != sizeB) {
  61. return Integer.compare( sizeA, sizeB );
  62. } else {
  63. return nameA.compareTo( nameB );
  64. }}
  65. ).forEach( s-> System.out.println(String.format( "== %s:%s",s.getKey(),s.getValue())) );
  66. }
  67.  
  68. private static boolean heroExists(String command, Map<String, List<String>> heroes) {
  69. if (heroes.containsKey( command )) {
  70. return true;
  71. }
  72. return false;
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement