HackerRank Java- Iterator




In this problem you need to complete a method func. The method takes an ArrayList as input. In that ArrayList there is one or more integer numbers, then there is a special string "###", after that there are one or more other strings. A sample ArrayList may look like this:

element[0]=>42
element[1]=>10
element[2]=>"###"
element[3]=>"Hello"
element[4]=>"Java"
You have to modify the func method by editing at most 2 lines so that the code only prints the elements after the special string "###". For the sample above the output will be:

Hello
Java



  1. import java.util.*;
  2. public class Main{
  3. static Iterator func(ArrayList mylist){
  4. Iterator it=mylist.iterator();
  5. while(it.hasNext()){
  6. Object element = it.next();
  7. if(element instanceof String)//Hints: use instanceof operator
  8. break;
  9. }
  10. return it;
  11. }
  12. @SuppressWarnings({ "unchecked" })
  13. public static void main(String []args){
  14. ArrayList mylist = new ArrayList();
  15. Scanner sc = new Scanner(System.in);
  16. int n = sc.nextInt();
  17. int m = sc.nextInt();
  18. for(int i = 0;i<n;i++){
  19. mylist.add(sc.nextInt());
  20. }
  21. mylist.add("###");
  22. for(int i=0;i<m;i++){
  23. mylist.add(sc.next());
  24. }
  25. Iterator it=func(mylist);
  26. while(it.hasNext()){
  27. Object element = it.next();
  28. System.out.println((String)element);
  29. }
  30. }
  31. }




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