Good, as I formulate in the question that is my big doubt. The counter doesn't work well and there are also times when compiling it doesn't give me the number 24 and the loop ends, could you help me?
public static void main(String[] args) {
System.out.println("Realiza un programa que genere números aleatorios pares del 0 al 100 y que no acabe hasta"
+ "que no saque el número 24. El programa tendrá que decir cuantos números se han generado.");
int contador = 1;
for (int i = 1 ; i!=24 ; i++){
int aleatorio = (int)(Math.random() * (100 + 1));
i=aleatorio;
contador++;
if(i%2==0){
System.out.println(i);
}
if(i==24){
System.out.println("Lo hemos intentado " + contador + " veces");
break;
}
}
}
}
I will proceed to explain your error and then fix it.
I took your code a bit and corrected it a bit, but it was only to find the error
The problem you have, is HOW are you using the FOR.
The FOR, has the following structure:
At the moment of giving a condition of
i!=24
is where you are failing !!!At the moment of
i
being equal to 23, a is producedi++
, thus increasing the value of i by 1, causingi=24
and stopping the for.That's why the code stops.
Now, the solution is as follows: USING A DO-WHILE