为了账号安全,请及时绑定邮箱和手机立即绑定

我对代码中的 while 循环有疑问

我对代码中的 while 循环有疑问

互换的青春 2021-09-03 16:21:26
当它变为零时,如何通过使用 playerHP 强制停止 while 循环?有时我会在它周围放置一个 If 语句,但它不起作用。编码新手,因此提供一些提示也很酷。:)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.");        }    }}}
查看完整描述

2 回答

?
桃花长相依

TA贡献1860条经验 获得超8个赞

通过break在修改playerHP后立即添加一个小于或等于零的检查后。喜欢,


playerHP -= bossDMG;

if (playerHP <= 0) {

    break;

}

// ...


查看完整回答
反对 回复 2021-09-03
?
回首忆惘然

TA贡献1847条经验 获得超11个赞

将 if 条件放在 playerHP -= bossDMG 之后;

如果(玩家HP < 1)中断;

当 playerHP 值小于等于 0 时,这将中断 while 循环。


查看完整回答
反对 回复 2021-09-03
  • 2 回答
  • 0 关注
  • 170 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信