对于我的作业,我试图抛出异常,以便我的程序不允许对象" Wolf"吃"植物"。然而,我正在努力寻找实现这一目标的方法。到目前为止,我尝试使用if语句来搜索食物的条件(x)等于"植物"但这似乎没有用。这是代码:
动物类
abstract public class Animal
{
String name;
int age;
String noise;
abstract public void makeNoise();
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
abstract public Food eat(Food x) throws Exception;
}
食品类
public class Food {
//field that stores the name of the food
public String name;
//constructor that takes the name of the food as an argument
public Food(String name){
this.name = name;
}
public String getName() {
return name;
}
}
食肉动物类
public class Carnivore extends Animal
{//if statement that throws exception
public Food eat(Food x) throws Exception
{
if (x.equals(new Meat("Plants"))) {
throw new Exception("Carnivores only eat meat!");
} else {
return x;
}
}
public void makeNoise()
{
noise = null;
}
public String getNoise()
{
return noise;
}
}
肉类
public class Meat extends Food
{
public Meat(String name) {
super(name);
}
public String getName() {
return super.getName();
}
}
狼类
public class Wolf extends Carnivore
{
Wolf()
{
name = "Alex";
age = 4;
}
public void makeNoise()
{
noise = "Woof!";
}
public String getNoise()
{
return noise;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String eat(String x)
{
return x;
}
}
主要
public class Main {
public static void main(String[] args)
{
Wolf wolfExample = new Wolf();
System.out.println("************Wolf\"************");
System.out.println("Name = " + wolfExample.getName());
System.out.println("Age = " + wolfExample.getAge());
wolfExample.makeNoise();
System.out.println("Noise = " + wolfExample.getNoise());
Meat meatExample = new Meat("Plants");
System.out.println("************Wolf eating habits************");
System.out.println("Wolves eat " + wolfExample.eat(meatExample.getName()));
}
}
输出
************Wolf"************
Name = Alex
Age = 4
Noise = Woof!
************Wolf eating habits************
Wolves eat Plants//this should throw exception message
非常感谢有关如何解决此问题以获得所需输出的任何帮助,谢谢。
答案 0 :(得分:0)
此代码导致问题:
if (x.equals(new Meat("Plants"))) {
throw new Exception("Carnivores only eat meat!");
} else {
return x;
}
此表达式:
x ==(新肉("植物"))
始终为false - new运算符创建Meat对象的新实例,因此引用始终不同。
所以你的代码应该是这样的:
public Food eat(Food x) throws Exception
{
if (x instanceof Meat) {
return x;
} else {
throw new Exception("Carnivores only eat meat!");
}
}
在这种情况下,您需要定义扩展Food的Plant类。
或者,您可以在Food类中定义比较名称字段的equals方法。 How to override equals method in java