Reputation: 18103
I am working on a little tiny game, where there is a Attacker and a Defender.
Player Attacker = new Player();
Player Defender = 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 have commented inside the code above, where i wish to have a if statement to determine how many dices it should have.
If this is not possible to do, another way of doing this maybe?
I also tried to
Attacker.tarningar = 3;
Defender.tarningar = 2;
right under where the object gets defined in main, but it doesn't work, because it has already ran Player()
inside class.
(I'm still new to java) Thanks
Upvotes: 3
Views: 137
Reputation: 10151
Change your code to this:
Player Attacker = new Player(true);
Player Defender = new Player(false);
class Player {
boolean attacker;
int armees = 0;
int tarningar = 0;
Dice Dices[];
Player(boolean attacker) {
this.attacker = attacker;
armees = 10;
tarninger = attacker ? 3 : 2;
Dices= new Dice[tarningar];
for(int i = 0; i < Dices.length; i++) {
Dices[i] = new Dice();
}
}
}
Upvotes: 2
Reputation: 108937
If you are trying to differentiate based on variable names, it's not possible because that information is removed during compiler optimizations. If the instances are accessible, you could do
if (this == attacker)
{
...
}
or you could introduce a new field to store name
Player attacker = new Player("Attacker");
or perhaps an enum.
Player attacker = new Player(PlayerType.Attacker);
Upvotes: 1
Reputation: 137282
You should add a variable determining whether this is an attacker or a defender. Or even better, if they do different things, create subclasses for attacker and defender.
Upvotes: 2
Reputation: 138864
Maybe you could do:
Player(boolean isAttacker){
armees = 10;
// if object name is Attacker, tarninger = 3, 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 will need to tell the player if it is attacking or defending when it is constructed.
Player p = new Player(true); // creates an attacker
Upvotes: 2