Peebl Peebl - 1 month ago 7
Java Question

How to break out of an if statement mid way | java

I have an if statement (turn based attacks) if there an easy way to break out of the if statement so that the enemy doesn't attack back if it's already dead?

Hopefully without doing another if statement equal to the one I already have. Just sounds stupid to have 2 of the same if statements inside each other.

The simplest way would be for the While loop to break out as soon as the Enemy dies I guess. But I'm not the expert.

while (!monster.isDead() && !player.isDead())
{
HashSet<String> input = reader.getInput();

if(input.contains("attack")) {
int playerAttack = player.attack();
int monsterAttack = monster.attack();

if (monster.getMonsterLiv() > 0)
{
monster.getAttacked(playerAttack);
System.out.println(Utilities.battleString(player.getName(), monster.getMonsterNavn(), playerAttack, monsterAttack, monster.getMonsterLiv()));
overView += "\n" + Utilities.battleString(player.getName(), monster.getMonsterNavn(), playerAttack, monsterAttack, monster.getMonsterLiv());

player.getAttacked(monster.attack());
System.out.println(Utilities.battleString(monster.getMonsterNavn(), player.getName(), monsterAttack, playerAttack, player.getHealth()));
overView += "\n" + Utilities.battleString(monster.getMonsterNavn(), player.getName(), monsterAttack, playerAttack, player.getHealth());
} else {
monster.getAttacked(playerAttack);
System.out.println(player.getName() + " attacks " + monster.getMonsterNavn() + " for " + playerAttack + " damage, and kills the " + monster.getMonsterNavn());
overView += "\n" + player.getName() + " attacks " + monster.getMonsterNavn() + " for " + playerAttack + " damage, and kills the " + monster.getMonsterNavn();
}
}
else if (input.contains("run"))
{
player.setGold(player.getGold() - 50);
break;
}
else {
System.out.println("Unknown word, try \"attack\" or \"run\" instead!");
}
}


The way I've done this might be slightly weird. Any formatting tips for the code is also welcome!

Answer

Change the contents of your attack routine as follows:

int playerAttack = player.attack();
int monsterAttack = monster.attack();

monster.getAttacked(playerAttack);
//etc

if (monster.getMonsterLiv() > 0)
{
    player.getAttacked(monster.attack());
    //etc
} else {
    //The monster dies from massive damage!
}

The idea is that you always apply the player's attack to the monster, and then you only apply the player's attack to the monster if the monster has lives left.

This way you don't have to "break out" of your logic; the next loop iteration will automatically end.