Limited access

Upgrade to access all content for this subject

The numbers array contains an array of increasing integers.

Which of the following methods will take this array as its parameter and return the number of groups of consecutive integers?

For example, if the numbers array contains {3, 9, 10, 11, 15, 17, 18, 20, 21, 22, 25}, then the method should return 3, since there are three groups of consecutive integers: first group is 9, 10, 11, second group is 17, 18, and third group is 20, 21, 22.

A
public static int groupsOfConsecutiveInts(int[] numbers)
{
    int count = 0;
    for (int i=1; i<numbers.length; i++)
    {
        if (numbers[i]== numbers[i-1]+1)
        {
            count = count+1;
        }
    }
    return count;
}
B
public static int groupsOfConsecutiveInts(int[] numbers)
{
    int count = 0;
    boolean isConsecutive = false;
    for (int i=1; i<numbers.length; i++)
    {
        if (numbers[i]== numbers[i-1]+1)
        {
            if (!isConsecutive)
                count = count+1;
            isConsecutive = true;
        }
        isConsecutive = false;
    }
    return count;
}
C
public static int groupsOfConsecutiveInts(int[] numbers)
{
    int count = 0;
    for (int i=1; i<numbers.length; i++)
    {
        if (numbers[i] == numbers[i-1]+1 && 
            numbers[i-1] !=  numbers[i-2]+1)
        {
            count = count+1;
        }
    }
    return count;
}
D
public static int groupsOfConsecutiveInts(int[] numbers)
{
    int count = 0;
    boolean isConsecutive = false;
    for (int i=1; i<numbers.length; i++)
    {
        if (numbers[i]== numbers[i-1]+1)
        {
            if (!isConsecutive)
                count = count+1;
            isConsecutive = true;
        }
        else
            isConsecutive = false;
    }
    return count;
}
E
public static int groupsOfConsecutiveInts(int[] numbers)
{
    int count = 0;
    for (int i=1; i<numbers.length; i++)
    {
        if (numbers[i] == numbers[i-1]+1 && 
            numbers[i-1] !=  numbers[i-2]+1 && i>1)
        {
            count = count+1;
        }
    }
    return count;
}
Select an assignment template