[英]I have a question about the while loop in my code
How do I make the while loop stop forcefully by using playerHP when it becomes zero?当它变为零时,如何通过使用 playerHP 强制停止 while 循环? Sometimes I would put an If statement around it, but it wouldn't work.有时我会在它周围放置一个 If 语句,但它不起作用。 New to coding so it would be cool to give some tips too.编码新手,因此提供一些提示也很酷。 :) :)
public class RPGFight {
public static void main (String args[]) {
int playerHP = 30;
int boss1HP = 420;
int exp = 0;
System.out.println("You open the chamber door to see what lies beyond.");
System.out.println("A demogorgon jumps out and attacks!");
System.out.println("You deftly pull out your mighty blade and defend youself");
while (boss1HP > 0) {
if (boss1HP > 0) {
int hit1 = (int)(Math.random()*20);
int hit2 = (int)(Math.random()*20);
int hit3 = (int)(Math.random()*20);
int hit4 = (int)(Math.random()*20);
int hit5 = (int)(Math.random()*20);
int hit6 = (int)(Math.random()*20);
int bossDMG = (int)(Math.random()*5);
System.out.println("\nYou hit the demogorgon for " + hit1 + " points of damage");
System.out.println("You hit the demogorgon for " + hit2 + " points of damage");
System.out.println("You hit the demogorgon for " + hit3 + " points of damage");
System.out.println("You hit the demogorgon for " + hit4 + " points of damage");
System.out.println("You hit the demogorgon for " + hit5 + " points of damage");
System.out.println("You hit the demogorgon for " + hit6 + " points of damage");
System.out.println("You have been hit for " + bossDMG + " points of damage");
playerHP -= bossDMG;
boss1HP -= hit1+hit2+hit3+hit4+hit5+hit6;
}
if (boss1HP < 0) {
int expbattle = (int)(Math.random()*126+5);
exp += expbattle;
System.out.println("\nThe demogorgon falls to the floor, lifeless.");
System.out.println("Congratulations! You earned " + expbattle + " points of experience.");
}
}
}
}
Put the if condition after playerHP -= bossDMG;将 if 条件放在playerHP -= bossDMG 之后;
if (playerHP < 1) break;如果(玩家HP < 1)中断;
this will break the while loop when playerHP value is less than equal to 0.当 playerHP 值小于等于 0 时,这将中断 while 循环。
By adding a break
immediately after you modify the playerHP
after checking that is less than or equal to zero.通过在检查小于或等于零后修改playerHP
后立即添加break
。 Like,喜欢,
playerHP -= bossDMG;
if (playerHP <= 0) {
break;
}
// ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.