如果 2 种不同的动物具有不同的构造函数,如何使用继承将它们添加到文本文件中?
How to add 2 different animals into a text file using inheritance, if they have different constructors?
我正在尝试使用继承将 2 种不同的动物添加到文本文件中,猫和狗。问题是,它们有不同的构造函数,我不确定如何将它们分别放入程序中的同一个文本文件中,因为该程序还使用用户界面。
我不确定我是否理解你的问题。
您有一个文本文件,其中写入了狗和猫的信息。你想将它们传递到你的程序中。
该文本文件是否在您的控制之下?当你开始读它的时候,你能理解它是猫还是狗?像
animal type: cat
animal name: fluffy
...
如果是:
int numAnimals = infile.nextInt();
infile.nextLine();
kennel.setName(kennelName);
for (int i = 0; i < numAnimals; i++) {
if(infile.nextLine().equals("cat")) {
Cat cat = readCat(infile);
kennel.addAnimals(cat);
}
else if(infile.nextLine().equals("dog")){
Dog dog = readDog(infile);
kennel.addAnimals(dog);
}
}
public Dog readDog(Scanner infile) {
//same as your dog reading part except the last part
return new Dog(animalName, owners, likesBones, favFood,
feedsPerDay);
}
为猫写同样的方法就可以了。由于狗class是从动物class继承而来的,所以狗也是一种动物。因此,您可以将它作为动物添加到您的动物列表中。希望对您有所帮助。
我正在尝试使用继承将 2 种不同的动物添加到文本文件中,猫和狗。问题是,它们有不同的构造函数,我不确定如何将它们分别放入程序中的同一个文本文件中,因为该程序还使用用户界面。
我不确定我是否理解你的问题。
您有一个文本文件,其中写入了狗和猫的信息。你想将它们传递到你的程序中。
该文本文件是否在您的控制之下?当你开始读它的时候,你能理解它是猫还是狗?像
animal type: cat
animal name: fluffy
...
如果是:
int numAnimals = infile.nextInt();
infile.nextLine();
kennel.setName(kennelName);
for (int i = 0; i < numAnimals; i++) {
if(infile.nextLine().equals("cat")) {
Cat cat = readCat(infile);
kennel.addAnimals(cat);
}
else if(infile.nextLine().equals("dog")){
Dog dog = readDog(infile);
kennel.addAnimals(dog);
}
}
public Dog readDog(Scanner infile) {
//same as your dog reading part except the last part
return new Dog(animalName, owners, likesBones, favFood,
feedsPerDay);
}
为猫写同样的方法就可以了。由于狗class是从动物class继承而来的,所以狗也是一种动物。因此,您可以将它作为动物添加到您的动物列表中。希望对您有所帮助。