2
I am doing some algorithms in various languages and in Java I come across a problem, in my function researcher when the value is not found in the list it should return me a None or null, but I can’t get one of the two, but if I order him to return 0 it works, but this wrong, I don’t want him to return it, I want him to warn me that the value entered in the item
.
public class PesquisaBinaria {
public static void main(String[] args) {
int[] minhaLista = { 1, 3, 5, 7, 9 };
for (int i : minhaLista) {
System.out.print(i + " ");
}
System.out.println(" ");
System.out.println("Procurando endereço do número o 3 ~: " + pesquisa_binaria(minhaLista, 3));
System.out.println("Procurando endereço do número o -1 ~:" + pesquisa_binaria(minhaLista, -1));
}
public static int pesquisa_binaria(int lista[], int item) {
for (int i = 0; i < lista.length; i++) {
int baixo = 0;
int alto = lista.length - 1;
while (baixo <= alto) {
int meio = (baixo + alto) / 2;
int chute = lista[meio];
if (chute == item) {
return meio;
} else if (chute > item) {
alto = meio - 1;
} else {
baixo = meio + 1;
}
}
}
return 0;
} }
what returns
1 3 5 7 9
Procurando endereço do número o 3 ~: 1
Procurando endereço do número o -1 ~:0
I say None because in Python I used it in case the item is not found
Your function cannot return
null
because their return is of the primitive typeint
. If you want to return null, change the function to return oneInteger
, then yes, you can return anull
.– Celso Marigo Jr
I believe it is because you are using primitive variables and they do not accept null try to use Wrappers, if you do not know what it is, see this link Wrappers in java
– Luis Fernando