我声明了两个对象的问题。一个工作正常,p1,而另一个,p2,无法解析为我方法的象征。
这两个对象位于main中,而方法位于Player类中。我试过移动变量和对象,但无济于事,因为它会导致范围的其他问题。
这是范围问题吗?但那么为什么在方法中看到一个对象而一个不是?对整个面向对象的东西也是新的,它让我陷入了一个循环。
错误是“无法解析符号'p2'”
下面的代码是到目前为止的主要方法,然后是其中一个有p2错误的方法。
提前感谢你的帮助。
public static void main(String[] args) {
Player p1 = new Player(name1); // instantiation of player 1 object; given first player's name
Player p2 = new Player(name2); // instantiation of player 2 object; given second player's name
}
public void attack1(Player p1) { // first method in which player 2 attacks player 1
Random rnd = new Random(); // instantiation of new random object
int dmg = rnd.nextInt(26) - 1; // setting of variable dmg to = a random number between 0 and 25
if (dmg >= 0 && dmg <= 15) { // if statement checking if dmg is between 0 and 15
p1.health = p1.health - dmg; // if dmg is between 0 and 15, reduce value from player 1 health
System.out.printf("%s attacked %s and %s's health is now %d.", p2.name, p1.name, p1.name, p1.health); // print to screen results of attack1
} else if (dmg > 15) { // if dmg value is greater than 15, player 2 misses player 1
System.out.printf("%s attacked %s and missed.", p2.name, p1.name); // print to screen results of missed attack1
}
答案 0 :(得分:0)
问题是p2
未在函数attack1
的范围内定义。要么将p1
和p2
传递给attack1
,要么制作班级的p1
和p2
个实例变量。
public void attack1(Player p1, Player p2) { // first method in which player 2 attacks player 1
Random rnd = new Random(); // instantiation of new random object
int dmg = rnd.nextInt(26) - 1; // setting of variable dmg to = a random number between 0 and 25
if (dmg >= 0 && dmg <= 15) { // if statement checking if dmg is between 0 and 15
p1.health = p1.health - dmg; // if dmg is between 0 and 15, reduce value from player 1 health
System.out.printf("%s attacked %s and %s's health is now %d.", p2.name, p1.name, p1.name, p1.health); // print to screen results of attack1
} else if (dmg > 15) { // if dmg value is greater than 15, player 2 misses player 1
System.out.printf("%s attacked %s and missed.", p2.name, p1.name); // print to screen results of missed attack1
}
作为旁注,我建议您删除attack1
和(可能)attack2
,而是编写方法public void attack(Player source, Player target)
以减少重复代码的数量。
public void attack(Player source, Player target) {
Random random = new Random();
int damage = random.nextInt(26) - 1;
if(damage >= 0 && damage <= 15) {
target.health -= damage;
System.out.printf("%s attacked %s and %s's health is now %d.", source.name, target.name, target.name, target.health);
} else if(damage > 15) {
System.out.printf("%s attacked %s and missed.", source.name, target.name);
}
}