noobprogrammer
noobprogrammer

Reputation: 523

Finding the max value in and Array

I have looked at other questions but not exactly the issue that I am facing here, This is the current code that I have

public class Qn3 {
    public static void displayHighestMark(String[] names,int[] marks, int count)
    {
        int mark = 0;
        int currentArrayPosition;
       for(int i=0;i <= names.length;i++)
       {

          if(mark <= marks[i])
              mark = marks[i];
          currentArrayPosition  = i;
       }
       System.out.println(name[i]+" with marks "+mark);
    }

    public static void main(String[] args)
    {
        String[] names = new String[]{"jack","hello","A","b","c","d"};// = new String[];

         int[] marks = new int[]{1,2,3,8,5,6};
        displayHighestMark(names,marks, 45);
    }

}

So basically I am trying to find the highest mark in the marks array. But I am getting expection of ArrayIndexOutOfBoundsException

Upvotes: 2

Views: 163

Answers (3)

kosa
kosa

Reputation: 66677

 for(int i=0;i <= names.length;i++)

should be

 for(int i=0;i < names.length;i++)

Because you are trying to get marks for index which is outside the range you got ArrayIndexOutOfBoundsException. Array index starts from 0, so when you do looping and lookup always need to look for < instead of <=

Please read this tutorial.

EDIT:

if(mark <= marks[i])
{
              mark = marks[i];
          currentArrayPosition  = i;
}

Upvotes: 5

Ahmed Hammad
Ahmed Hammad

Reputation: 445

You should change

for(int i=0;i <= names.length;i++)

to

for(int i=0;i < names.length;i++)

because in you are trying to access an item outside of the array when variable i is equal to names.length because the array's index is beginning from 0 to array's length - 1

Upvotes: 0

Robin Chander
Robin Chander

Reputation: 7425

Change loop to

for(int i=0;i < names.length;i++)

Moreover, why do you need count variable as one of method params. You are not using it.

Upvotes: 0

Related Questions