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

当它变为零时,如何通过使用 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.");

        }

    }

}

}



互换的青春
浏览 172回答 2
2回答

桃花长相依

通过break在修改playerHP后立即添加一个小于或等于零的检查后。喜欢,playerHP -= bossDMG;if (playerHP <= 0) {&nbsp; &nbsp; break;}// ...

回首忆惘然

将 if 条件放在&nbsp;playerHP -= bossDMG 之后;如果(玩家HP < 1)中断;当 playerHP 值小于等于 0 时,这将中断 while 循环。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java