public class AnimalException extends Exception {
public AnimalException(String error) {
super(error);
}
}
public class Zoo {
private String animal;
private String food;
public Zoo (String animal, String food) throws AnimalException {
this.animal = animal;
if (findWord(animal, "wolf")) {
throw new AnimalException("This animal is a predator.");
//something ought to be done here, I reckon
}
else {
this.food = food;
}
}
public static boolean findWord(String word, String find) {
int total = 0;
int idx = 0;
while ( (idx = word.indexOf(find, idx))!= -1 ) {
total++;
idx++;
}
if (total == 0) {
return false;
}
else {
return true;
}
}
What I would like to do is when a wolf
is caught in the constructor the value for food
is changed automatically to something else. I did try using getter-setters
, however, I get the error of unreachable code
.
What do I do?
If you want some specific logic to be performed when you detect a "wolf", an exception is not the right way. You should only throw an exception if the construction of the instance should fail when you find a "wolf".
public Zoo (String animal, String food) {
this.animal = animal;
if (findWord(animal, "wolf")) {
// put whatever logic you wish here
}
else {
this.food = food;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With