I tried to write simple program and stuck at some point into while loop.
From current output I see that it only print the same data.
But it should be executed at every iteration.
Snippet of code:
public void fight(Droid first, Droid second) {
while (first.isAlive() & second.isAlive()) {
if ((random.nextInt(10) + 1) % 2 == 0) {
shoot(first, second);
} else {
shoot(second, first);
}
// testing output
System.out.printf("Droid %s has %d power level%n", first.getName(), first.getPower());
System.out.printf("Droid %s has %d power level%n", second.getName(), second.getPower());
}
if (first.getPower() <= 0) {
fightResult(second);
} else {
fightResult(first);
}
}
And here is output:
Droid John has 5 power level
Droid Dik has 8 power level
Droid John has 5 power level
Droid Dik has 8 power level
Droid John has 5 power level
Droid Dik has 8 power level
Droid John has 5 power level
Droid Dik has 8 power level
I made some silly mistake and couldn't find one.
Update:
here is shoot()
:
private void shoot(Droid first, Droid second) {
second.setPower(first.getImpact());
}
and Droid
class:
public abstract class Droid {
protected Random random;
private String name;
private int power;
private int impact;
public Droid(int aPower, int anImpact) {
power = aPower;
impact = anImpact;
}
public String getName() {
return name;
}
public void setPower(int aPower) {
power = aPower;
}
public void setImpact(int anImpact) {
impact = anImpact;
}
public int getPower() {
return power;
}
public int getImpact() {
return impact;
}
public abstract void fight(Droid first, Droid second);
public boolean isAlive() {
boolean result = false;
if (this.getPower() > 0) result = true;
return result;
}
}
- How to solve this trouble?
Your shoot method is incorrect, it keeps setting the droids to each other's impact value.
I suspect you'd want to subtract the impact from the droid's power instead.
Something along the lines of
or somewhat more OO-style: