HackerRank Java- Annotations




Your task is to complete the FaimilyBudget annotation and the FamilyMember class so that the Solutiion class works perfectly with the defined constraints.



  1. import java.lang.annotation.*;
  2. import java.lang.reflect.*;
  3. import java.util.*;
  4. @Target(ElementType.METHOD)
  5. @Retention(RetentionPolicy.RUNTIME)
  6. @interface FamilyBudget {
  7. String userRole() default "GUEST";
  8. int budgetLimit() default 0; // edited line
  9. }
  10. class FamilyMember {
  11. @FamilyBudget(userRole = "SENIOR", budgetLimit = 100) // added line
  12. public void seniorMember(int budget, int moneySpend) {
  13. System.out.println("Senior Member");
  14. System.out.println("Spend: " + moneySpend);
  15. System.out.println("Budget Left: " + (budget - moneySpend));
  16. }
  17. @FamilyBudget(userRole = "JUNIOR", budgetLimit = 50) // added line
  18. public void juniorUser(int budget, int moneySpend) {
  19. System.out.println("Junior Member");
  20. System.out.println("Spend: " + moneySpend);
  21. System.out.println("Budget Left: " + (budget - moneySpend));
  22. }
  23. }
  24. public class Solution {
  25. public static void main(String[] args) {
  26. Scanner in = new Scanner(System.in);
  27. int testCases = Integer.parseInt(in.nextLine());
  28. while (testCases > 0) {
  29. String role = in.next();
  30. int spend = in.nextInt();
  31. try {
  32. Class annotatedClass = FamilyMember.class;
  33. Method[] methods = annotatedClass.getMethods();
  34. for (Method method : methods) {
  35. if (method.isAnnotationPresent(FamilyBudget.class)) {
  36. FamilyBudget family = method
  37. .getAnnotation(FamilyBudget.class);
  38. String userRole = family.userRole();
  39. int budgetLimit = family.budgetLimit(); // edited line
  40. if (userRole.equals(role)) {
  41. if(spend <= budgetLimit){ // edited line
  42. method.invoke(FamilyMember.class.newInstance(),
  43. budgetLimit, spend);
  44. }else{
  45. System.out.println("Budget Limit Over");
  46. }
  47. }
  48. }
  49. }
  50. } catch (Exception e) {
  51. e.printStackTrace();
  52. }
  53. testCases--;
  54. }
  55. }
  56. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube