HackerRank Java- Varargs - Simple Addition


You are given a class Solution and its main method in the editor.
Your task is to create the class Add and the required methods so that the code prints the sum of the numbers passed to the function add.

  1. import java.io.*;
  2. import java.lang.reflect.*;
  3. import java.util.*;
  4. import java.text.*;
  5. import java.math.*;
  6. import java.util.regex.*;
  7. class Add {
  8. void add(int... numbers) {
  9. StringBuffer sb = new StringBuffer();
  10. int sum = 0;
  11. for (int num : numbers) {
  12. sb.append(num + "+");
  13. sum += num;
  14. }
  15. sb.setCharAt(sb.length() - 1, '=');
  16. sb.append(sum);
  17. System.out.println(sb);
  18. }
  19. }
  20. public class Solution {
  21. public static void main(String[] args) {
  22. try{
  23. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  24. int n1=Integer.parseInt(br.readLine());
  25. int n2=Integer.parseInt(br.readLine());
  26. int n3=Integer.parseInt(br.readLine());
  27. int n4=Integer.parseInt(br.readLine());
  28. int n5=Integer.parseInt(br.readLine());
  29. int n6=Integer.parseInt(br.readLine());
  30. Add ob=new Add();
  31. ob.add(n1,n2);
  32. ob.add(n1,n2,n3);
  33. ob.add(n1,n2,n3,n4,n5);
  34. ob.add(n1,n2,n3,n4,n5,n6);
  35. Method[] methods=Add.class.getDeclaredMethods();
  36. Set<String> set=new HashSet<>();
  37. boolean overload=false;
  38. for(int i=0;i<methods.length;i++)
  39. {
  40. if(set.contains(methods[i].getName()))
  41. {
  42. overload=true;
  43. break;
  44. }
  45. set.add(methods[i].getName());
  46. }
  47. if(overload)
  48. {
  49. throw new Exception("Overloading not allowed");
  50. }
  51. }
  52. catch(Exception e)
  53. {
  54. e.printStackTrace();
  55. }
  56. }
  57. }

download android app