Java: detect object name?

I'm playing a little game with an attacker and a defender

Player Attacker = new Player();
        Player Deffender = new Player();

    }
}
class Player{
    int armees = 0;
    int tarningar = 0;
    Dice Dices[];
    Player(){
        armees = 10;
        // if object name is Attacker,tarninger = 3,if defender = 2
        Dices= new Dice[tarningar];
        for(int i=0;i<Dices.length;i++){
            Dices[i]=new Dice();
        }
    }
}

I commented on the above code, and I want an IF statement to determine how many dice it should have

If this is impossible, what about another way?

I tried, too

Attacker.tarningar = 3;
Deffender.tarningar = 2;

Define the location of the object in main, but it won't work because it already runs player () in the class

(I'm still new to Java) thank you

Solution

Maybe you can do this:

Player(boolean isAttacker){
    armees = 10;
    // if object name is Attacker,if defender = 2
    int diceNum;
    if (isAttacker) diceNum = 2;
    else diceNum = 3;
    Dices= new Dice[diceNum];
    for(int i=0;i<Dices.length;i++){
        Dices[i]=new Dice();
    }
}

Then you need to tell the player whether it is attacking or building defense

Player p = new Player(true); // creates an attacker
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>