Zanon05
Zanon05

Reputation: 3

Returning index vector

1- Hey i'm noob at programing but if you guys help i would apreciate it , i need in this method to return the max value of the vector that it will recive from main method but i also need to return to main method the index of with the max value was caught , so how can i do it?

  public static int maxOfaVector (int[] vector){
    int max = vector[0];
    int school;
      for(int i=0; i<vector.length; i++){
        if(vetor[i] > vector[0]){
        max = vector[i];
        }
     }
      return max;
  }

Upvotes: 0

Views: 31

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

No, a method can return one and only one value. Fortunately that's all that's needed here since all you need to do is to have the method return the index of the max value just as it's already written to do. Once you have that, the calling code can easily get the max value from the array.

// in the main method
// assuming an int array called myArray
int maxIndex = maxOfaVector(myArray);
int maxValue = myArray[maxIndex];

Problems though:

  • Your code has a typo, if(vetor[i] should be if (vector[i]
  • And a logic error. In the same if boolean test, you should test if (vector[i] > vector[max]) not if (vector[i] > vector[0])
  • Also, you should test to make sure that the array has length > 0 first.

Upvotes: 2

Related Questions