Vector Search - Arrayindexoutofboundsexception

Asked

Viewed 35 times

2

I’m building a function that does a linear search on an arrangement. What I would like is that instead of leaving in the call the value of the size of the arrangement, I would like to use the property length so that she herself can calculate its size and so make the call. Only whenever I put the vet.length makes the mistake 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 mistake:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
    at buscavalor.BuscaValor.buscaValor(BuscaValor.java:9)
    at buscavalor.BuscaValor.main(BuscaValor.java:22)
  • Error occurs search methodLinear, add this method in question.

  • @Articuno Actually it’s all searchValor, it was my mistake when copying. Already edited.

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 because in the way you did, when passing vet.length (7), the method buscaValor will try to access the array at position 7, but positions only go from 0 to 6. The positions of an array in Java always go from 0 to 0 array.length - 1.

Therefore, the solution is to exchange vet.length for vet.length - 1.

  • Wow, I totally forgot about that. Thank you.

  • @Andersonlessa If you have no further doubt about this question, click on what appears below the voting number of this answer to mark it as accepted and mark your question as resolved. It was a pleasure to help you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.