1.Write a method countPositives that when passed an LinkedList of Double objects, returns the number of positive items in the LinkedList. The method should return 0 if the list is null or empty.
2.Write a method countMatches that when passed an LinkedList of String objects and a String target, returns the number of items in the list that contains target. The method should return 0 if the list is null or empty. For example, if list = [\"thereby\", \"they\", \"proved\", \"the\", \"other\", \"guy\", \"was\", \"the\", \"father\"] and target = \"the\", the method should return 6, as there are six Strings con- taining \"the\".
3.Add a method count that when passed an LinkedList<Integer> list, returns the number of prime numbers in list.
Solution
Part 1
This below code will count the number of positive numbers in a given linked list
public static int countPositives(LinkedList<double> list)
{
int count = 0;
if(list == NULL)
return 0;
else
{
Iterator<double> itr=al.iterator();
while(itr.hasNext())
{
if(itr.next() > = 0);
count++;
else
return 0;
}
}
Part 2:
This below code will count the number of matching strings with given target in a given linked list
public static int countMatches(LinkedList<String> list, String target)
{
int count = 0;
String temp;
if(list == NULL)
return 0;
else
{
Iterator<String> itr=al.iterator();
while(itr.hasNext())
{Â Â temp = itr.next();
if( temp.compareTo(target))
count++;
else
return 0;
}
}
Part 3:
This below code will count the number of prime numbers in a given linked list
public static int countPrimeNumbers(LinkedList<Integer> list)
{
int count = 0;
if(list == NULL)
return 0;
else
{
Iterator<Integer> itr=list.iterator();
while(itr.hasNext())
{
if(isPrime(itr.next()))
count++;
else
return 0;
}
}
return count;
}
private boolean isPrime(int n)
{
for(int i=2;i<n;i++)
{
if(n%i==0)
return false;
}
return true;
}
.