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)