3

I'm a newbie who is trying to complete the below tutorial

    // Create a method called countEvens
    // Return the number of even ints in the given array. 
    // Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1. 
/*
 * SAMPLE OUTPUT:
 *  
 * 3
 * 0
 * 2
 *  
 */

Below is my code

public static void main(String[] args) {

        int a[] = {2, 1, 2, 3, 4};
         countEvens(a); // -> 3
         int b[] = {2, 2, 0};
         countEvens(b); // -> 3
         int c[] = { 1, 3, 5};
         countEvens(c); // -> 0

    }


    public static void countEvens(int[] x){
        int i = 1;
        int count = 0;
        while ( i <= x.length){
            if (x[i] % 2 == 0){
                count ++;
            }
            i ++;
        }
        System.out.println(count);
    }

The code can be run, but I get the below error message

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at apollo.exercises.ch05_conditionals.Ex5_CountEvens.countEvens(Ex5_CountEvens.java:23)
    at apollo.exercises.ch05_conditionals.Ex5_CountEvens.main(Ex5_CountEvens.java:10)

May I know what I'm doing wrong here?

0

4 Answers 4

3

The line

while ( i <= x.length)

should be

while ( i < x.length)

If the length of xis 5, for example, the indices are 0, 1, 2, 3 and 4. The index goes from 0 up to one less than the length of the array.

However the tidiest way to do this is to use a for each loop rather than a while loop:

public static void countEvens(int[] x) {
    int count = 0;
    for (int number : x)
        if (number % 2 == 0)
            count++;
    System.out.println(count);
}
Sign up to request clarification or add additional context in comments.

Comments

2

'i' should go from 0 to length()-1, because array indices start at 0, and the index of the last element is length()-1.

Therefore, a correct version of your code would be:

public static void countEvens(int[] x){
    int i = 0;
    int count = 0;
    while ( i < x.length){
        if (x[i] % 2 == 0){
            count ++;
        }
        i ++;
    }
    System.out.println(count);
}

For your specific purpose, a for loop would be simpler.

for(int i = 0; i< x.length(); i++){
  if(x[i]%2==0){
  count++;
  }
}

Comments

1

At while ( i <= x.length), you're looping until i is equal to the length of x. The last index of an array is always length - 1, so change the less-than-or-equals (<=) to just less-than (<). Also, initialize i to 0, as Java arrays are zero-based.

3 Comments

the problem isn't iterating over the array too many times, it is that arrays are zero based and the OP assumes 1 based
It is, actually. Covering it up with i - 1 is a poor solution.
it isn't, actually. The OP iterates 5 times, but 1~5 rather than 0~4. Not TOO MANY times, but in the wrong position. I agree that i-1 isn't pretty, but it is the quickest solution. BUT you're right. Starting at 0 and iterating to i < x.length is the best solution, mentioned in my post...
0

Arrays in Java (and most other languages) are indexed starting at 0. However the length of an array is the count of the elements in the array. So for your array a[]

int a[] = {2,1,2,3,4};

The index goes up to 4, whereas the length is 5.

You are getting an index out of bounds error because you are iterating through the array from 1~5 because of the <= (less than equal to) operator, but the indices of the array are 0~4. When you access each element of the array you should use

if (x[i-1] % 2 == 0) //iterates from 0~4 rather than 1~5

otherwise you can set the iterator int i = 0; and use the less than < operator to ensure the iterator moves 0~4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.