Vector search - ArrayIndexOutOfBoundsException

2

I'm building a function that does a linear search in an array. What I would like is that instead of leaving the value of the array size in the call, I would like to use the length property so that it can even calculate its size and thus make the call. But whenever I put the vet.length it gives the error ArrayIndexOutOfBoundsException , but if I put the 6 in the call it works.

What to do?

public static int buscaValor(int vet[], int maximo, int value) {

    if (maximo >= 0) {
        if (vet[maximo] == value) //(linha 9)
            return maximo;
        else
            return buscaValor(vet, maximo - 1, value);
    }
    return -1;
}

public static void main(String[] args) {
    Scanner read = new Scanner(System.in);
    int vet[] = {10, 2, 43, 14, 25, 6, 37};
    System.out.print("\n\nQual valor deseja buscar? - ");
    int respostaBusca = read.nextInt();
    int index = buscaValor(vet, vet.length, respostaBusca); //(linha 22)

    if (index == -1)
        System.out.println("Elemento não encontrado");
    else
        System.out.println("O índice do elemento " + respostaBusca + " é: " + index);
}

The error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
    at buscavalor.BuscaValor.buscaValor(BuscaValor.java:9)
    at buscavalor.BuscaValor.main(BuscaValor.java:22)
    
asked by anonymous 28.08.2017 / 01:18

1 answer

2

In particular, vet.length is 7 (there are 7 elements). If you pass as parameter 6, it works. The reason for this is that in the way you did, by passing vet.length (7), the buscaValor method will try to access the array in position 7, but positions only go from 0 to 6. The positions of an array in Java they always go from 0 to array.length - 1 .

So, the solution is to change vet.length by vet.length - 1 .

    
28.08.2017 / 01:51