Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why while loop isn't running and I do not know why

Whenever I run the code it just ends regardless of what coinFlip is.ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ

public void fight(String person, int theirHP){
    int yourHP = ThreadLocalRandom.current().nextInt(5, 30 + 1);
    System.out.println("Your HP: " + yourHP + "\nTheirHP: " + theirHP);
    int coinFlip = ThreadLocalRandom.current().nextInt(1, 2 + 1);
    int damage;
    System.out.println(coinFlip);
    if (coinFlip == 1) {
        while (yourHP <= 0 || theirHP <= 0) {
            damage = ThreadLocalRandom.current().nextInt(1, 3 + 1);
            theirHP -= damage;
            System.out.println("Their HP: " + theirHP + "\nYour HP: " + yourHP);
            damage = ThreadLocalRandom.current().nextInt(1, 3 + 1);
            yourHP -= damage;
            System.out.println("Their HP: " + theirHP + "\nYour HP: " + yourHP);
        }
    }
    if (coinFlip == 0) {
        while (yourHP <= 0 || theirHP <= 0) {
            damage = ThreadLocalRandom.current().nextInt(1, 3 + 1);
            yourHP -= damage;
            System.out.println("Their HP: " + theirHP + "\nYour HP: " + yourHP);
            damage = ThreadLocalRandom.current().nextInt(1, 3 + 1);
            theirHP -= damage;
            System.out.println("Their HP: " + theirHP + "\nYour HP: " + yourHP);
        }
    }
}

ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your while loops will only be entered when the condition evaluates as true. I would assume both yourHP and theirHP start with values greater than 0 so

while (yourHP <= 0 || theirHP <= 0)

evaluates as false. I believe you wanted

while (yourHP > 0 && theirHP > 0)

To end when either values decrease to 0.

Also, and not directly to your issue,

if (coinFlip == 1)

should logically be followed by an else. Not another test like if (coinFlip == 0). But both bodies appear to do the same thing, so it isn’t clear why you have coinFlip in the first place.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading