Answer the question
In order to leave comments, you need to log in
Why doesn't IF suddenly work?
Hello, I'm trying to solve the task "snail race" in which as soon as any of the "snails" scores 50 points, the game stops.
I don’t understand why it doesn’t work and the cycle ends somewhere around 18 or 20?
Whereas if you replace with - the principle works but a little crooked - the array is checked to ensure that all its elements have reached a state less than 50 - so while is not suitable.
I don't understand what's wrong? After all, when used for each element of the array, the program should be launched every time the element < 50 and for some reason it stops ..
Thank you!if (tab[z] < 50)
while (tab[z] < 50)
if
public static void main(String[] args) {
int dice;
int[] tab = new int[3];
System.out.println("\n\t -= SNAIL RUN =- ");
for (int z=0; z<tab.length;z++){
if (tab[z] < 50) {
System.out.println("\n");
for (int i=0; i<tab.length; i++) {
// Generating random numbers
dice = ThreadLocalRandom.current().nextInt(1, 6 + 1);
tab[i] += dice;
System.out.print("Dice"+(i+1)+"="+dice+" | ");
}
System.out.println("\n");
for (int i=0; i<tab.length; i++){
System.out.print(tab[i] + " | ");
}
System.out.println("\n________________________________________________________________");
}
}
System.out.println("\nGAME OVER");
Answer the question
In order to leave comments, you need to log in
Because all the application logic is run for each element from the tab.
It should be something like this:
int dice;
int[] tab = new int[3];
boolean gameOver = false;
System.out.println("\n\t -= SNAIL RUN =- ");
while (!gameOver) {
System.out.println("\n");
for (int i = 0; i < tab.length; i++) {
// Generating random numbers
dice = ThreadLocalRandom.current().nextInt(1, 6 + 1);
tab[i] += dice;
if (tab[i] > 50) {
gameOver = true;
}
System.out.print("Dice" + (i + 1) + "=" + dice + " | ");
}
System.out.println("\n");
for (int i = 0; i < tab.length; i++) {
System.out.print(tab[i] + " | ");
}
System.out.println("\n________________________________________________________________");
}
System.out.println("\nGAME OVER");
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question