我有一个错误,其中第61行声明变量firstbattlerealactualhealth
超出了要使用的范围。我尝试过各种各样的东西,但我似乎无法让它发挥作用。
如果你能告诉我什么是错的,以及我需要解决的问题,我将不胜感激。
编辑:更改了哪个变量和行有问题,因为我无法计算或阅读。
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 = firstenemyfirsthealth;
int firstenemynewhealth = firstenemyfirsthealth;
int firstenemyhitpoints = (int) Math.ceil(Math.random() * 25);
int firsthitpoints = 0;
boolean firstkill = true;
while (firstkill) {
if (firstattack > firstenemydefense) {
firsthitpoints = (int) Math.ceil(Math.random() * firstbattleattack);
System.out.println();
System.out.println("You did " + firsthitpoints + " damge to the Slime.");
}
firstenemynewhealth = firstenemyhealth - firsthitpoints;
if (firstenemynewhealth <= 0) {
firstkill = false;
}
if (firstattack <= firstenemydefense) {
System.out.println();
System.out.println("Attack failed!");
}
int firstbattleactualhealth = firstbattlehealth;
if (firstenemyattack > firstdefense) {
int firstenemyhitpointattack = (int) Math.ceil(Math.random() * firstenemyhitpoints);
int firstbattlerealactualhealth = firstbattleactualhealth - firstenemyhitpointattack;
System.out.println();
System.out.println("The enemy did " + firstenemyhitpointattack + " damage to you. You have " + firstbattlerealactualhealth + " health remaining.");
}
if (firstenemyattack <= firstdefense ) {
System.out.println();
System.out.println("Enemy attack missed!");
}
}
int firstenemyactualhealth = firstenemynewhealth;
if (firstenemyactualhealth <= 0){
System.out.println();
System.out.println("You won the battle!");
HP = firstbattlerealactualhealth;
EXP = firstbattleEXP + 20;
Gold = firstbattlegold + 20;
System.out.println();
System.out.println("You have " + HP + " health.");
System.out.println("You have earned" + EXP + " experience.");
System.out.println("You have earned" + Gold + " gold.");
firstbattle = false;
}
}
答案 0 :(得分:2)
可能是因为在firstbattlerealactualhealth
子句中定义了if
。如果程序未执行if
块,则不会定义firstbattlerealactualhealth
。你必须定义&amp;将它初始化到你确定它将被执行的地方。
最重要的是,如果你在一个块({}
)中定义一个变量,它应该仅在该块内使用,而不是在其他地方使用。
提示:
不要为任何变量first_sth
命名。最常见的是名称为second_sth
和third_sth
的变量,您将无法管理它们。你应该通过传递不同的参数为其他战斗(不仅是粘液)重用相同的逻辑,这样你就可以编写DRY(不要重复自己)代码。变量名也很易读。