You need to enable JavaScript to run this app. Java开发文本RPG战斗系统时while循环无法退出并重复输出攻击提示
优惠活动
大模型
产品
解决方案
定价
更多

Java开发文本RPG战斗系统时while循环无法退出并重复输出攻击提示

问题根因
  • 字符串比较方式错误
    注意,Java中==运算符对比的是对象内存引用地址,而非字符串本身的文本内容。你代码里写的if (combat == "n")永远无法匹配用户的实际输入,哪怕用户准确输入了"n",也不会进入后续的攻击逻辑块。
  • 战斗循环缺失核心状态更新逻辑
    你的while循环退出条件为En1HP > 0,但整个循环体全程没有修改过En1HP的数值。哪怕攻击逻辑可以正常触发,敌人血量也会一直保持初始的随机正值,循环永远不具备退出条件。两个错误叠加后,程序就会无限重复打印操作引导,读入用户输入却不执行任何有效战斗逻辑。
修复方案
  • 将字符串判断逻辑替换为标准的内容比较写法,使用"n".equals(combat)替代原有的combat == "n",这种写法还能规避输入为null时的空指针异常,是更稳妥的实现方式。
  • 在普通攻击的伤害计算流程中,追加敌人血量扣减代码,让循环可以在敌人血量归零时正常退出。
修复后完整可运行代码
import java.util.Scanner;
import java.util.Random;

public class RPGv1 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Random rand = new Random();

        System.out.println("What is your name?");
        String name = scan.nextLine();

        System.out.println("\nWelcome to RPGv1 " + name + "!");

        // 玩家基础属性
        int MaxHP = rand.nextInt(25) + 1;
        int MaxMP = rand.nextInt(20) + 1;
        int MaxStam = 15;

        // 敌人基础属性
        int En1HP = rand.nextInt(10) + 1;
        int En1Stam = rand.nextInt(5) + 1;

        // 战斗启动
        System.out.println("You are being approached by the evil Enemy 1!");

        while (En1HP > 0) {
            System.out.println("Type \"n\" to use your Normal Attack, \"h\" for your Heavy Attack, and \"f\" for your fireball.");
            String combat = scan.nextLine();
            // 修正后的字符串匹配逻辑
            if ("n".equals(combat)) {
                if (MaxStam >= 2) { // 普通攻击最低耐力门槛
                    int nDam = rand.nextInt(3) + 1; // 普通攻击随机伤害
                    int nStam = rand.nextInt(5) + 1; // 本次攻击随机消耗耐力
                    MaxStam = MaxStam - nStam; // 扣除玩家耐力
                    En1HP = En1HP - nDam; // 扣除敌人血量
                    System.out.println("You have dealt " + nDam + " damage, and have " + MaxStam + " Stamina remaining.");
                    System.out.println("Enemy 1 has " + En1HP + " HP remaining.");
                } else {
                    System.out.println("You do not have enough stamina.");
                }
            }
        }
        // 战斗结束提示
        System.out.println("You defeated Enemy 1!");
        scan.close();
    }
}

内容的提问来源于stack exchange,提问作者Agustus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.27 01:15:03