user1605782
user1605782

Reputation: 111

Manipulating arrays in Java. Stuck on difficult homework task

I am brand new to Java and am learning it in a programming course this semester. We have a homework assignment due and I am struggling. I appreciate this will be easy for the experienced programmers out there but for me it's a head scratcher. Here's the first question.

public int countInRange(int[] data, int lo, int hi)

For this, you have to count the number of elements of the array, data, that lie in the range >>lo to hi inclusive, and return the count. For example, if data is the array {1, 3, 2, 5, 8} >>then the call

countInRange(data, 2, 5)

should return 3 because there are three elements, 3, 2 and 5 that lie in the range 2 .. 5.

And here is what I have done so far:

/**
 * Count the number of occurrences of values in an array, R, that is
 * greater than or equal to lo and less than or equal to hi.
 *
 * @param  data  the array of integers
 * @param  lo   the lowest value of the range
 * @param  hi   the highest value of the range
 * @return      the count of numbers that lie in the range lo .. hi
 */
public int countInRange(int[] array, int lo, int hi) {
    int counter = 0; 
    int occurrences = 0;
    while(counter < array.length) {
        if(array[counter] >= lo) {
            occurrences++; 
        }
        counter++;
    }
    return occurrences;
}

Upvotes: 0

Views: 1217

Answers (4)

Bohemian
Bohemian

Reputation: 424993

With arrays and Collections in java, you may use a foreach loop, and especially when you're learning, "less code" is (usually) easier to understand, because the code that's left is just the important stuff.

On the other hand, if you want to construct your own loop, always use a for loop - updating the loop variable within a while loop (when it's unnecessary) is considered poor style because it can lead to nasty bugs.

The answer is so simple, it's hardly worth making you work it out from cryptic hints:

public int countInRange(int[] array, int lo, int hi) {
    int occurrences = 0;
    for (int element : array) {
        if (element >= lo && element <= hi) {
            occurrences++;
        }
    }
    return occurrences;
}

Upvotes: 1

hugohabel
hugohabel

Reputation: 724

for ( int i = 0; i < array.length; i++ ) {
    if ( array[i] >= lo && array[i] <= hi ) {
        occurrences++;
    }
}

Use for statement to iterate an array.

Upvotes: 1

Kevin
Kevin

Reputation: 25269

You're missing the upper bound check in your if statement.

Upvotes: 1

kosa
kosa

Reputation: 66637

if(array[counter] >= lo && conditionforhighcheck)
{
//Then only update occurence count
}

Because of homework,I didn't type in code. I gave a pointer.

Upvotes: 6

Related Questions