Good, it may seem like a silly question but I'm doing a method that is passed by an integer parameter and when it matches the position of a vector, I return the value that is in that position. What would be the correct syntax? ? Thanks in advance.
Good, it may seem like a silly question but I'm doing a method that is passed by an integer parameter and when it matches the position of a vector, I return the value that is in that position. What would be the correct syntax? ? Thanks in advance.
First you must verify that the whole value that your method receives is less than the length of the vector, if it is, you proceed to return the value of the vector using that number received as index
private int devuelveNum( int numeroRecibido ){
if(numeroRecibido < mivector.length){
return mivector[numeroRecibido];
}
return null;
}
The condition must be numeroRecibido < mivector.length
because you must remember that mivector.length
will result in the number of objects in the vector, 8 for example. But the indexes start from 0, so the index of the last object will be 7.
0 1 2 3 4 5 6 7 índice
| ojb1 | obj2 | obj3 | obj4 | obj5 | obj6 | obj7 | obj8 | vector de objetos
If you receive a parameter 8 and you make mivector[8]
it will search in index 8 which does not exist. You will receive an index exception outside of Rank.
The last return
is because all the paths of a code must return something in a function.