gpt4 book ai didi

java - BlueJ 找不到变量

转载 作者:行者123 更新时间:2023-11-30 03:05:18 24 4
gpt4 key购买 nike

我正在尝试设置第一次战斗,但在第 24 行,BlueJ 告诉我变量 firsthitpoints 不可见,无法执行。

如果有人能告诉我这段代码有什么问题,我将不胜感激

  if (characterquality == "Slayer"){
int HP = 150;
int Attack = 75;
int Defense = 50;
int MP = 20;
int EXP = 0;
int Gold = 50;

boolean firstbattle = true;
while (firstbattle){
int firstbattlehealth = HP;
int firstbattleattack = Attack;
int firstbattledefense = Defense;
int firstbattleMP = MP;
int firstbattleEXP = EXP;
int firstbattlegold = Gold;

int firstattack = (int) Math.ceil(Math.random() * 6);
int firstdefense = (int) Math.ceil(Math.random() * 6);

int firstenemyattack = (int) Math.ceil(Math.random() * 6);
int firstenemydefense = (int) Math.ceil(Math.random() * 6);

int firstenemyhealth = (int) Math.ceil(Math.random() * 50);

int firstenemyhitpoints = (int) Math.ceil(Math.random() * 25);
boolean firstkill = true;
while (firstkill) {
if (firstattack > firstenemydefense){
int firsthitpoints = (int) Math.ceil(Math.random() * firstbattleattack);

}
int firstenemynewhealth = firstenemyhealth - firsthitpoints;

if (firstenemynewhealth <= 0){
firstkill = false;
}
if (firstattack <= firstenemydefense){
System.out.println("Attack failed!");
}
if (firstenemyattack > firstdefense){
int firstenemyhitpointattack = (int) Math.ceil(Math.random() * firstenemyhitpoints);
System.out.println("The enemy did " + firstenemyhitpointattack + " damage to you. You have " + firstbattlehealth + " health remaining.");
}
if (firstenemyattack <= firstdefense){
System.out.println("Enemy attack missed!");
}
}
int firstenemynewhealth = firstenemynewhealth;
if (firstenemynewhealth <= 0){
firstbattle = false;
}
}
}

最佳答案

您在前面的 if block 中定义变量,将其移到 block 外并为其指定初始值。比如,

boolean firstkill = true;
int firsthitpoints = 0; // <-- declare and initialize.
while (firstkill) {
if (firstattack > firstenemydefense){
firsthitpoints = Math.ceil(Math.random() * firstbattleattack);
}
int firstenemynewhealth = firstenemyhealth - firsthitpoints;
// ...

此外,不是直接针对您的问题,不要将 String 相等性与 ==.

if (characterquality == "Slayer"){

应该是

if (characterquality.equals("Slayer")) {

也许它适用于您的情况,但这只是测试引用相等性(而不是值相等性)。另请参阅How do I compare strings in Java?

最后,执行比较指令需要成本1。您应该使用 else block ,而不是将逻辑反转与多个 if 进行比较。比如,

if (firstenemyattack > firstdefense) { 
int firstenemyhitpointattack = (int) Math.ceil(Math.random()
* firstenemyhitpoints);
// Presumably, firstbattlehealth -= firstenemyhitpointattack here?
System.out.println("The enemy did " + firstenemyhitpointattack
+ " damage to you. You have " + firstbattlehealth
+ " health remaining.");
} else { // <-- An "else" block, firstenemyattack <= firstdefense
System.out.println("Enemy attack missed!");
}

1尽管在现代环境中很小。

关于java - BlueJ 找不到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34964046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com