package Files; // a cat that knows how to turn itself into CSV public class Cat { private String name; private int age; private double weight; private boolean hungry; public Cat() { setName("Kitty"); setAge(0); setWeight(1); setHungry(true); } public Cat(String name, int age, double weight) { this(); setName(name); setAge(age); setWeight(weight); } public Cat(Cat original) { this(); if (original != null) { setName(original.getName()); setAge(original.getAge()); setWeight(original.getWeight()); // skip hungry } } public String getName() { return name; } public void setName(String name) { if (name != null) { this.name = name; } } public int getAge() { return age; } public void setAge(int age) { if (age >= 0) { this.age = age; } } public double getWeight() { return weight; } public void setWeight(double weight) { if (weight >= 0) { this.weight = weight; } } public boolean getHungry() { return hungry; } public void setHungry(boolean hungry) { this.hungry = hungry; } public Cat clone() { return new Cat(this); } public boolean equals(Object other) { if (other != null && other instanceof Cat) { Cat cTemp = (Cat) other; // ignore hungry return getName().equals(cTemp.getName()) && getAge() == cTemp.getAge() && getWeight() == cTemp.getWeight(); } return false; } public String toString() { return "cat named " + getName() + " (" + getAge() + "yo, " + getWeight() + "lbs)"; } // make comma separated representation of a Cat public String toCSV() { // in keeping with equals and copy, not preserving hungry value for long term return getName() + "," + getAge() + "," + getWeight(); } // turn comma separated data into a cat // method marked static, but didn't have to be public static Cat fromCSV(String line) { Cat result = null; // can't do anything with no data if (line != null) { // split the line at the commas, creating an array String[] elements = line.split(","); // only try to make a cat if there are the right number of elements if (elements.length == 3) { try { // name is already a String String newName = elements[0]; // convert String to int int newAge = Integer.parseInt(elements[1]); // convert String to double double newWeight = Double.parseDouble(elements[2]); // by our powers combined: a kitty result = new Cat(newName, newAge, newWeight); // if they didn't give an int and a double in their strings // they don't get a cat, choosing not to complain about it } catch (NumberFormatException e) { // just silently seething about bad data } } } return result; } }