-1
I have an exercise that searches a number on a predetermined vector; and answers "was found and which vector position" or answers that "the number is not in the vector". I wanted the explanation of why to use the boolean achou = false
and of query if (!achou)
. I know the program has to display 2 results whether or not you found the number, but I didn’t quite understand what the use of the boolean
and his denial in if
are doing.
public static void main(String[] args) {
int vetor[] = { 1, 3, 5, 7, 9}; // Cria o vetor com valores pré-definidos
int numero;
boolean achou = false; // Variável para armazenar o resultado da procura
System.out.println ("Qual número deseja procurar? ");
numero = Integer.parseInt(JOptionPane.showInputDialog(null,"Qual número deseja procurar?"));
for (int posicao = 0; posicao < 5; posicao++)
{
if (vetor[posicao] == numero)
{
System.out.println ("Encontrado na posição: "+ posicao+ "\n");
achou = true;
}
}
if (! achou)
{
System.out.println ("O número não está no vetor\n");
}
}
}
!achou
is the same thing asachou == false
, is just a fancy way of writing– Natan Fernandes
That one
achou
exists because in the case of not having found it can only know after having traversed the whole vector. I agree that it is unnecessary, abreak
would eliminate this and solve an inefficiency (if ever thought about why keep going?). In fact (being a little annoying because I turn around and commit this sin) the design is not good, there should be a function that only travels and returns if you thought or not, and another that uses this to give this information to the user. The!
is the logic negation operator that comes from Boole algebra (optimal concept for a beginner in programming to study).– Piovezan
I spoke
break
? I meantreturn true
. :P Logic gave a failure now rs– Piovezan