import java.util.Random; /** * A Class to hold info about rabbits * Mostly as an illustration of comparable * @author gtowell * Created: Feb 2020 * Modified: Oct 17, 2020 * MOdified: Aug 9, 2021 */ public class Rabbit implements Comparable { /** An id */ private final int iD; /** The rabbit's nickname: flopsy, mopsy, peter, etc */ private final String nickname; /** * Create an instance of rabbit * @param breed the breed * @param id an ID number * @param nn a stirng nickname. If null, a random char set */ public Rabbit(int id, String nn) { this.iD = id; this.nickname = nn==null ? makeName() : nn; } /** * Default Constructor. * An random id and name */ public Rabbit() { this(new Random().nextInt(200000), null); } /** * Make a 7 lower case char random string. * @return a random string */ private String makeName() { Random r = new Random(); StringBuffer sb = new StringBuffer(); for (int i=0; i<7; i++) { char c = (char)('a' + r.nextInt(26)); sb.append(c); } return sb.toString(); } /** How to determine if two rabbits are the same */ public boolean equals(Rabbit otherRabbit) { return otherRabbit.getId()==iD; } public int getId() { return iD; } public String getNickName() { return nickname; } /** * A String rep of a rabbit */ public String toString() { return "[["+ iD + " " + nickname + "]]"; } /** Compare two rabbits based on their nicknames * Just use string compare :0) * */ @Override public int compareTo(Rabbit o) { int tmp = nickname.compareTo(o.getNickName()); if (tmp != 0) { return tmp; } return iD - o.getId(); } public static void main(String[] args) { System.out.println("Hello rabbit"); } }