For my assignment, I have been asked to carry out the following:
- Compare the ages of the Animals so that the animals can be ordered from highest to lower age.
I've created the if statements that should do this if I'm correct but I'm not sure how to refer to each Animal within the array list so I've used pseudocode and refereed to the first array in the ArrayList as "AL1" the second as "AL2" and so on.
Here is the code:
Demo class
import java.util.ArrayList;
public class Demo {
public static ArrayList<Animal> animalGroup; // make this an instance static variable to access in other class with main method;
public static void main(String[] args)
{
animalGroup = new ArrayList<>();
//Add new Animals with properties such as name and age?
animalGroup.add(new Wolf("Sam", 5));
animalGroup.add(new Parrot("George", 3));
animalGroup.add(new Wolf("Wesley", 7));
animalGroup.add(new Parrot("Pat", 10));
System.out.println("Compare Aimal ages" + AL1.getAge().compareTo(AL2.getAge, AL3.getAge(), AL4.getAge()));
int result = AL1AGE.compareTo(AL2AGE, AL3AGE, AL4AGE);
if(result == 3)
System.out.println(AL1.getName() + "comes before " + AL2.getName() + ", " + AL3.getName() + " and " + A|L4.getName());
if(result == 5)
System.out.println(AL2.getName() + "comes before " + AL3.getName() + ", " + AL4.getName() + " and after " + A|L1.getName());
if(result == 7)
System.out.println(AL3.getName() + "comes before " + AL4.getName() + " and after " + AL1.getName() + " and " + A|L2.getName());
else
System.out.println(AL4.getName() + "comes after " + AL1.getName() + ", " + AL2.getName() + " and " + A|L3.getName());
}
}
Main method call
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args)
{
System.out.println("************ArrayList after sorting************");
Collections.sort(animalGroup);
Collections.reverse(animalGroup);
for(Animal animal2 : animalGroup) {
System.out.println(animal2.getName()+","+animal2.getAge());
}
}
}
Desired output
Sam comes before George, Wesley and Pat
George comes before Wesley, Pat and after Sam
Wesley comes before Pat and after Sam and George
Pat comes after Sam, George and Wesley
Any help on how do accomplish the desired outcome would be much appreciated, thanks.