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

问题描述 投票:-2回答:1

我声明了两个对象的问题。一个工作正常,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
        }
java object
1个回答
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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.