Exostrike Exostrike - 5 months ago 14
Java Question

Java working out which number hits zero first

I'm building a simple fighting game to test out loops and if statements, however I've run into a kind of complex logic issue.

The loop ends when either the player or enemy HP hits zero however I've discovered that my code can't detect which HP hits zero first results in the player always winning.

Is there a simple way of tracking which number hits zero first therefor breaking the loop?

do {

Scanner reader = new Scanner(System.in);
System.out.println("1: Attack. 2: Defend");
int n = reader.nextInt();
if (n == 1){
} else if (n == 2){
PHP = (PHP-Math.max(0, EATK-PDEF));
System.out.println("P "+PHP);
while (PHP >= 1 || EHP >= 1);

if(PHP <= 0){
System.out.println("You Lose!");
}else if (EHP <= 0){
System.out.println("You win!");


Look at your loop continuation condition:

while (PHP >= 1 || EHP >= 1)

It means "while the player or his enemy can fight, go on". In other words, you continue fighting until they both die, at which point you declare the player the winner, even though it's a draw.

Changing the condition to ""while the player and his enemy can fight" will fix this problem.