I am looking for some help with my code. I want the program to read from a .txt file and create an Animal object and insert it into an ArrayList of Animal objects, based upon the data found in the file, with the presumption that the data in the file is formatted correctly.
I created a counter, to keep track of the line number. Since I know how the data in the .txt file is formatted, I can anticipate where one Animal object begins and another ends.
The issue I keep getting is that the animal objects in the ArrayList have the same fields as the last Animal in the text file. Any and all help is greatly appreciated.
BufferedReader userInputFile = null;
int ctr = 1;
try {
userInputFile = new BufferedReader(new FileReader(userDocFilePath));
Animal newFileAnimal = new Animal();
while((s = userInputFile.readLine()) != null) {
if (ctr == 1){
newFileAnimal.setName(s);
ctr++;
} else if (ctr == 2) {
newFileAnimal.setSpineStatus(s);
ctr++;
} else if (ctr == 3) {
newFileAnimal.setFurStatus(s);
ctr++;
} else if (ctr == 4) {
newFileAnimal.setSwimStatus(s);
System.out.printf("Animal name: %s\n\tSpine status: %s\n\t"
+ "Fur status: %s\n\tSwim status: %s\n", Animal.getName(),
+ newFileAnimal.getSpineStatus(),
+ newFileAnimal.getFurStatus(),
+ newFileAnimal.getSwimStatus());
array.add(newFileAnimal);
ctr = 1;
}
}
The text file looks like this:
Rabbit
true
true
true
Duck
true
false
true