For this program I have an arraylist for animals full of objects from two subclasses (Fish and Tiger class) I am having a hard time figuring out how to count each item type so I can print it out. I need it to say something like There are 3 tigers and 2 fish. Here is my code thus far
import java.util.*;
public class Menagerie{
public static void main(String [] args){
/* ArrayList to hold animal data */
ArrayList<Animal> alist = new ArrayList<Animal>();
/* object creations */
Tiger jtiger = new Tiger("Javan Tiger", "Tiger acreage #6");
Fish fnfish = new Fish("False network catfish", "Fresh Water");
Tiger btiger = new Tiger("Bengal tiger", "Ritchie area of RIT");
Fish shark = new Fish("Shark", "Salt Water");
Tiger stiger = new Tiger("Siberian Tiger", "Tiger acreage #4");
/* Adding objects to alist ArrayList */
alist.add(jtiger);
alist.add(fnfish);
alist.add(btiger);
alist.add(shark);
alist.add(stiger);
/* printing out animal information using toString() */
System.out.println("Report on animals...");
System.out.println(jtiger.toString());
System.out.println(fnfish.toString());
System.out.println(btiger.toString());
System.out.println(shark.toString());
System.out.println(stiger.toString());
}
}
Any help will be great! thanks.
1.) Iterate over alist
.
for(Animal animal : alist){
}
2.) Have two counters, one for tigerCount
and another for fishCount
.
3.) Check for instanceOf class
, and increment
accordingly.
for(Animal animal : alist){
if(animal instanceOf Fish){
fishCount++;
}else if(animal instanceOf Tiger){
tigerCount++;
}
}
instanceof keyword is a binary operator used to test if an object (instance) is a subtype of a given Type.
instanceof operator is used to check the type of an object at runtime. It is the means by which your program can obtain run-time type information about an object. instanceof operator is also important in case of casting object at runtime. instanceof operator return boolean value, if an object reference is of specified type then it return true otherwise false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With