Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider an array of integers as below: int[] a = {5, 2, -4, 3, 0, -5, 7, 11, 6,

ID: 3527010 • Letter: C

Question

Consider an array of integers as below: int[] a = {5, 2, -4, 3, 0, -5, 7, 11, 6, 13} a. Complete the method named count(int[] a) in the class Count. The method should return the number of positive numbers in the array. Thus count(a) should return 7 (not counting the 2 negative numbers and 0). b. On examining your code for count (your solution to part-a), you will see a test similar to this: if (a[i]>0) {...}. If we were to now ask you to modify the count method so that it counted the number of negative numbers, it would be trivial: All that you would have to do is change the greater-than comparison operator (

Explanation / Answer

/* OUTPUT
Number positive integers are 7
Number nagative integers are 2
Number even integers are 4
*/

import java.util.*;
class Predicate
{
public boolean test(int x)
{
return x>0;
}
}

class IsNegative extends Predicate // inheritance used here.
{
public boolean test(int x) // polymorphism used here
{
return x<0;
}
}

class IsEven extends Predicate // inheritance used here.
{
public boolean test(int x) // polymorphism used here
{
return x%2==0;
}
}

public class Count
{
/* public int count(int[] a)
{
int result = 0;
for(int i=0; i<a.length; i++)
{
if(a[i]>0) result++;
}
return result;
} */
public static int countIF( int[] a, Predicate p)
{
int result = 0;
for(int i=0; i<a.length; i++)
if(p.test(a[i])) result++;
return result;
}
public static void main(String[] args)
{
int[] a = {5, 2, -4, 3, 0, -5, 7, 11, 6, 13};
System.out.println("Number positive integers are "+ countIF( a, new Predicate()));
System.out.println("Number nagative integers are "+ countIF( a, new IsNegative()));
System.out.println("Number even integers are "+ countIF( a, new IsEven()));
}
}