I\'m getting an error whenever running this program??? I don\'t see why. Can any
ID: 3840165 • Letter: I
Question
I'm getting an error whenever running this program??? I don't see why. Can anyone help?
public class evenPercent{
public static void main(String[] args) {
double [ ] a = {3, 4, 5, 7, 8};
arraySum(a);
}
public static void arraySum(double[ ] a){
int sum = 0;
for(int i = 0; i <= a.length; i++){
double BusyP = a[i];
if(BusyP % 2 == 0){
sum++;
}
}
double percent = (sum)/(a.length);
System.out.println(percent + "% of your values are even");
}
}
Explanation / Answer
The for loop is executed for 6 times where as you array has 5 elements only.
Please change the for loop as below.
for(int i = 0; i < a.length; i++)
*************Modified code ***************************
public class evenPercent{
public static void main(String[] args) {
double [ ] a = {3, 4, 5, 7, 8};
arraySum(a);
}
public static void arraySum(double[ ] a){
int sum = 0;
for(int i = 0; i < a.length; i++){
double BusyP = a[i];
if(BusyP % 2 == 0){
sum++;
}
}
double percent = (sum)/(a.length);
System.out.println(percent + "% of your values are even");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.