The method I am working on is readDataFromFile()
. It reads a file that has data separated with Tabs
such as:
Bird Golden Eagle Eddie
Mammal Tiger Tommy
Mammal Lion Leo
Bird Parrot Polly
Reptile Cobra Colin
This is what I have been asked to do however I may not fully understand how to create this, any help would be much appreciated.
Question I have been given:
Spaces at the beginning or end of the line should be ignored. You should extract the three substrings and then create and add an Animal object to the zoo. You should ignore the first substring ("Bird" in the above example) as it is not required for this part of this project. Also note that, similar to the code you should have commented out, the addAnimal() method will require a third parameter "this" representing the owner of the collection. On successful completion of this step you will have a "basic" working version of readDataFromFile()
Zoo class:
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.hasNext())
{
String name = scanner.nextLine();
System.out.println("Animal: " + name);
}
}
Animal Class:
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;
}
}