This logic is wrong (I suggest you do the table test, it will be clear what is wrong).
Basically, you go through (I believe) all the elements, and if it is equal to 1, arrow the variable ganhador2
for false
, and if different, arrow to true
.
So actually what matters is the value of the last element found. If the latter is 1, the variable will be false
, else she will be true
, independent of all other values you have verified before.
If you are looking for an element, you start by indicating that you have not found it, and only change this statement if you find it. In general, it would be something like:
boolean encontrou = false; // antes do loop eu ainda não encontrei o elemento
for (int i = 0; i < elementos.length; i++) {
if (elementos[i] == valorQueEstouProcurando) {
encontrou = true;
break; // encontrei, posso parar de procurar
}
}
That is, if I found the element, I indicate that I found it (I change the value of the flag) and I may even interrupt the loop with break
(because if I have already found, it makes no sense to keep looking).
But in your case there are two loops nested, and the break
by default interrupts the most internal, so if you want to interrupt the for
external just use a label:
boolean ganhador2 = true;
busca: for (int i = 0; i < tabelaUser.length; i++) {
for (int j = 0; j < tabelaUser[i].length; j++) {
if (tabelaUser[i][j] == 1) {
ganhador2 = false;
break busca; // encontrei, interrompe a busca
}
}
}
Notice I used length
instead of a fixed value such as 10
. So the code works for arrays of any size.
And if you just want to scroll through the values, you don’t have to iterate through the indexes, you can do so (assuming that tabelaUser
be a int[][]
):
boolean ganhador2 = true;
busca: for (int[] linha: tabelaUser) {
for (int n: linha) {
if (n == 1) {
ganhador2 = false;
break busca; // encontrei, interrompe a busca
}
}
}
specify better what you’re looking for, primitive, object... what type?
– André Martins