Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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");
  
}
  
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote