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.
– user28595
@Articuno Actually it’s all searchValor, it was my mistake when copying. Already edited.
– Anderson Lessa