Java,两个对象,一个无法在方法中解析,其他可以

时间:2018-03-01 01:53:58

标签: java object

我声明了两个对象的问题。一个工作正常,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
        }

1 个答案:

答案 0 :(得分:0)

问题是p2未在函数attack1的范围内定义。要么将p1p2传递给attack1,要么制作班级的p1p2个实例变量。

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);
    }
}