/* Bunny.java example code AC Chapin */ package conditionals; // a Bunny with name and carrotcount, using conditionals public class Bunny { public String name; // name of the Bunny... defaults to null public int carrotCount; // how many carrots eaten // increase the number of carrots public void feed() { carrotCount++; System.out.print("Thanks! I now have " + carrotCount + " nummy carrots!"); if (carrotCount > 100) { System.out.print(" And I'm full!"); } System.out.println(); // so we get a newline after anything else we printed } // the bunny hops public void hop() { if (name != null) { System.out.println(name + " the Bunny just hopped!"); } else { System.out.println("The Bunny just hopped!"); } } // toString method creates String representing the Bunny // whenever a Bunny is implicitly cast to a String @Override // netbeans likes to do this public String toString() { // creating a string for part of the result String carrotDescription = "no"; // default to no carrots // if there are carrots, change the description to include them if (carrotCount != 0) { carrotDescription = carrotCount + ""; } // returning different strings for different results // if there is no name, don't include "null" // but if there is, do include the name if (name == null) { // the variable we set up before is included in what we return return "a bunny with " + carrotDescription + " carrots"; } else { return "a bunny named " + name + " with " + carrotDescription + " carrots"; } } // run around like crazy public void marchMadness() { if (name != null) { System.out.println(name + " runs around crazily until knocking itself out against a tree. Poor " + name); } else { System.out.println("A bunny runs around crazily until knocking itself out against a tree. Poor thing."); } } // print a greeting public void sayHi() { if (name != null) { System.out.println("Hi! My name is " + name + " and I'm a Bunny!"); } else { System.out.println("Hi! I'm a Bunny!"); } } }