java - Using enhanced for loop to return the index of the largest number in an array -


i'm having issue using foreach loop find index of largest number in array.

i getting: "exception in thread "main" java.lang.arrayindexoutofboundsexception: 5"

i appreciate if me out. thanks! here code:

   public static int enhanintmax(int[] a){     int largeindex =0;     int largearrnum=scores[0];     for( int : a){         if(a[i] >largearrnum){``             largearrnum += a[i];             largeindex += i;          }     }     return largeindex;         }    public static void main(string[] args){   int[] a={1,2,3,4,5};  system.out.println(enhaninmax(a)); } 

i'm sure you've worked out comments, trouble here :

if(a[i] > largearrnum) 

won't try compare element value of against largearrnum, rather ith element of a. using enhanced loop, "for(int = 0; < blah blah blah... " part of loop handled you. rather iterate across indices of array, enhanced loop iterates across contents. therefore, if @ point value of a[i] greater length, you'll error. right way fix replace "a[i]" "i", might want give site quick review first: https://blogs.oracle.com/corejavatechtips/entry/using_enhanced_for_loops_with


Comments