Nice, I wonder how "isDead" is implemented though...
Why, the implementation of isDead() is obvious!
public boolean isDead() {
boolean dead = false;
if(isAlive() == true) dead = isAlive();
if(isAlive() == false) dead = !isAlive();
return dead;
}
And if you feel that is just leaving Schrödinger's cat in the box:
public class Critter {
// Given
public boolean isAlive(){
boolean alive = false;
if(isDead() == true) alive = isDead();
if(isDead() == false) alive = !isDead();
return alive;
}
private boolean dead = false;
private int counter = 0;
private boolean isDead() {
if(dead) {
++counter;
return dead && counter % 2 == 0;
}
return dead;
}
public void squish() {
dead = true;
}
}
Now we can take our critters for a quick spin:
public class Main {
private static String describeStatus(Critter critter) {
return critter.isAlive() ? "very much alive" : "a little worse for wear";
}
private static String describeStep() {
double random = Math.random();
if(random < 1.0 / 3.0) {
return "Squish!";
} else if(random < 2.0 / 3.0) {
return "Squelch!";
}
return "Crunch!";
}
public static void main(String [] args) {
Critter critter = new Critter();
System.out.println("What a lovely little critter! I sure hope nothing happens it!");
if(Math.random() < 0.5) {
System.out.println(describeStep());
critter.squish();
System.out.println("Oh dear, I accidentally stepped on it. Poor thing is looking " + describeStatus(critter) + " now...");
} else {
System.out.println("Close call, I narrowly avoided it. It is looking " + describeStatus(critter) + " now...");
}
}
}
I hate it when I find actual code which looks not unlike this, bugs in one area worked around by equally crazy stuff somewhere else.