Hi, it may seem like a silly question but I am creating a method that passes an integer as a parameter and when it matches the position of a vector, it returns the value in that position. What would be the correct syntax? Thanks in advance.
Hi, it may seem like a silly question but I am creating a method that passes an integer as a parameter and when it matches the position of a vector, it returns the value in that position. What would be the correct syntax? Thanks in advance.
First you must verify that the integer 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 an index
The condition must be
numeroRecibido < mivector.length
because you must remember thatmivector.length
it will return the number of objects in the vector, 8 for example. But the indices start from 0, so the index of the last object will be 7.If you receive a parameter 8 and do
mivector[8]
it will look at index 8 which does not exist. You will receive an index out of range exception.The latter
return
is because all paths in a code must return something in a function.