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?
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);
}
'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++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With