Reputation: 97
Part of my main
try{
Scanner read = new Scanner(file);
int fix = read.nextInt();
do{
for(int x = 0; x < fix; x++){
String petname = read.next();
int birthday = read.nextInt();
String species = read.next();
double bill = read.nextDouble();
String owner = read.next();
Veterinarian work = new Veterinarian(petname, birthday, species, bill, owner);
Veterinarian.Vet.add(work);
}
}
while(read.hasNextLine() == pick);
}
catch(FileNotFoundException FNF){
System.err.format("File not found");}
this is my class
static List<Veterinarian> Vet = new ArrayList<>();
public Veterinarian(){}
public Veterinarian(String petname, int birthday, String species, double bill, String owner){
this.petname = petname;
this.birthday = birthday;
this.species = species;
this.bill = bill;
this.owner = owner;
Vet.add(this);
}
I don't know why the add method I'm using is creating two copies of the object into two separate ArrayList's. Thanks for the help!
Upvotes: 0
Views: 82
Reputation: 44808
Because you're adding it twice...
String owner = read.next();
Veterinarian work = new Veterinarian(petname, birthday, species, bill, owner);
Veterinarian.Vet.add(work); // once
...
public Veterinarian(String petname, int birthday, String species, double bill, String owner){
this.petname = petname;
this.birthday = birthday;
this.species = species;
this.bill = bill;
this.owner = owner;
Vet.add(this); // twice
}
Also note, it would be better practice to remove the second invocation (in your constructor).
Upvotes: 1
Reputation: 344
the add method is called twice, when you new a instance of Veterinarian using
Veterinarian work = new Veterinarian(petname, birthday, species, bill, owner)
,
the add method has been called, and you call it again after that
Veterinarian.Vet.add(work);
Upvotes: 0
Reputation: 763
You are adding it in the constructor:
Vet.add(this);
and you are adding it in the main:
Veterinarian.Vet.add(work);
Upvotes: 1