我专注于方法readDataFromFile()
,它可以读取文本分隔的数据,例如:
Bird Golden Eagle Eddie
Mammal Tiger Tommy
Mammal Lion Leo
Bird Parrot Polly
Reptile Cobra Colin
目前,我已使用扫描仪方法分隔了每个单词,例如:Reptile, Cobra. Colin
。
Animal
包括:name
和species
。
任何指导我如何实现此目标的帮助或建议都将非常令人惊奇。
MyZoo类:
public class MyZoo
{
private String zooId;
private int nextAnimalIdNumber;
private TreeMap<String, Animal> animals;
private Animal animal;
public MyZoo(String zooId)
{
this.zooId = zooId.trim().substring(0,3).toUpperCase();
nextAnimalIdNumber = 0;
animals = new TreeMap<String, Animal>();
}
public String allocateId()
{
nextAnimalIdNumber++;
String s = Integer.toString(nextAnimalIdNumber);
while ( s.length()<6 )
s = "0" + s;
return zooId + "_" + s;
}
public void addAnimal(Animal animal)
{
animals.put(animal.getName(), animal);
this.animal = animal;
}
public void readDataFromFile() throws FileNotFoundException
{
int noOfAnimalsRead = 0;
String fileName = null;
JFrame mainWindow = new JFrame();
FileDialog fileDialogBox = new FileDialog(mainWindow, "Open", FileDialog.LOAD);
fileDialogBox.setDirectory(".");
fileDialogBox.setVisible(true);
fileName = fileDialogBox.getFile();
String directoryPath = fileDialogBox.getDirectory();
File dataFile = new File (fileName);
Scanner scanner = new Scanner(dataFile);
//System.out.println("The selected file is " + fileName);
scanner.next();
while(scanner.hasNextLine())
{
String type = scanner.next();
String species = scanner.next();
String name = scanner.next();
System.out.println(species + ": " + name);
scanner.nextLine();
}
scanner.close();
}
}
动物类:
public class Animal
{
private String id;
private String species;
private String name;
public Animal(String species, String name, MyZoo owner)
{
id = owner.allocateId();
this.species = species;
this.name = name;
}
public String getId()
{
return id;
}
public String getName()
{
return name;
}
public String getSpecies()
{
return species;
}
public String toString()
{
return id + " " + name + ": a " + species;
}
}
答案 0 :(得分:0)
找到名称和物种后,就可以使用Animal
的构造函数创建实例,然后将其添加到您的动物园中:
while(scanner.hasNextLine()){
String type = scanner.next();
String species = scanner.next();
String name = scanner.next();
System.out.println(species + ": " + name);
scanner.nextLine();
Animal a = new Animal(species, name, this); // 'this' bevcause its requires a MyZoo
this.addAnimal(a);
// can inline : addAnimal(new Animal(species, name, this));
}