I wrote a program using sorting to first sort an array list by the last name of the entries and then by there age, thus creating 2 lists as the output. The problem is the last name sort seems to work good but the age sort always puts the names in the same order as the last name sort. Here is my code so far, I have 2 classes.
package myperson;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Queue implements Comparable<Queue> {
public Person Data;
public int iter=0;
public Queue(String first, String last,int age)
{
Data = new Person(first, last, age);
}
@Override
public int compareTo(Queue other)
{
if(iter==0){
iter++;
return Data.Last.compareTo(other.Data.Last);
}
else
return Double.compare(Data.Age, other.Data.Age);
}
@Override
public String toString() {
return Data.First + " " + Data.Last;
}
public static void main(String[] args) throws java.io.IOException {
ArrayList list = new ArrayList();
String first;
String last;
int age = 0;
Scanner sc=new Scanner(System.in);
list.add(new Queue("John", "Huber", 22));
list.add(new Queue("Chelsea", "Davis", 32));
list.add(new Queue("Susan", "Taylor", 46));
list.add(new Queue("Scott", "Zedburg", 59));
System.out.println("Ordered by Last Name");
Collections.sort(list);
for (int i = 0; i < list.size(); i++)
{
System.out.println(list.get(i));
}
System.out.println("\nSort by Age");
Collections.sort(list);
for (int i = 0; i < list.size(); i++)
{
System.out.println(list.get(i));
}
}
}
Person class:
package myperson;
public class Person {
public String First;
public String Last;
public double Age;
public Person(String first, String last,double age)
{
First = first;
Last = last;
Age = age;
}
}
Output:
run:
Ordered by Last Name
Chelsea Davis
John Huber
Susan Taylor
Scott Zedburg
Sort by Age
Chelsea Davis
John Huber
Susan Taylor
Scott Zedburg
BUILD SUCCESSFUL (total time: 0 seconds)