Question

Exercise 4.b Answer the following questions for the method count () below: public static int count (List list, Object element
0 0
Add a comment Improve this question Transcribed image text
Answer #1

If you have any doubts, please give me comment...

import java.util.*;

public class CountElements{

public static void main(String[] args) {

List<Integer> list = new ArrayList<Integer>();

list.add(3);

list.add(3);

list.add(1);

System.out.println("Count is: "+count(list, 3));

List<Integer> list2 = new ArrayList<Integer>();

list2.add(1);

list2.add(7);

list2.add(5);

System.out.println("Count is: "+count(list2, 2));

}

public static int count(List<Integer> list, int search){

if(list==null)

throw new NullPointerException("List must not be empty");

else{

int count = 0;

for(Integer el: list){

if(el==search)

count++;

}

if(count==0)

return -1;

else

return count;

}

}

}

Add a comment
Know the answer?
Add Answer to:
Exercise 4.b Answer the following questions for the method count () below: public static int count...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT