Sorting an array of objects

hi there, i have to sort an array of object that looks like:
surname, name, age, height
well i have to sort them alphabetically like this:
based on the surnames, if the surnames are the same than sort on the base of the names; if the names are the same sort them on the base of age and so on. If all the fields are the same the order is non important.
Well I am not sure how I can do it using the Comparable Interface? as it is an interface i don't have any idea how to implement it

This search took 2 seconds to do. And it's using your exact subject header. Next time try searching, instead of waiting forever hoping that someone will help you.
http://search.java.sun.com/search/java/index.jsp?col=javaforums&qp=&qt=%2B%22sorting+an+array+of+objects%22

Similar Messages

  • How to sort an array of objects?

    I need to sort an array of objects. Each object has serial number, and other properties. I need to sort it by serial number.

    Do a java.util.Arrays.sort(). The method has quite a few overloads, so I'll give a complete example this time:import java.util.*
    public class SortDemo {
        public static void main(String args) {
            SimpleObject[] objs = new SimpleObject[10];
            for (int i=0; i<10; i++)
                objs=new SimpleObject();
    dump(objs);
    Comparator c = new SimpleComparator();
    Arrays.sort(objs, c);
    dump(objs);
    static void dump(Object[] o) {
    for (int i=0; i<o.length; i++)
    System.out.print(o[i] + " ");
    /** Object to demonstrate comparing with **/
    class SimpleObject {
    private int n = (int) (10*Math.random());
    public String toString() {
    return String.valueOf(getNumber());
    public int getNumber() {return n;}
    /** The custom comparator **/
    class SimpleComparator implements Comparator {
    public int compare(Object o1, Object o2) {
    return ((SimpleObject) o1).getNumber() - ((SimpleObject) o2).getNumber();
    public boolean equals(Object o) {return false;}
    }I could have made the SimpleObject class "Comparable", but a design like this allows more flexibility so I decided to use another class for the Comparator.

  • Sorting an array of objects and returning another variable

    Hi there,
    Bit stuck on this one I wonder if anyone can help..
    I have an object array into which I've pushed a number of objects with different variables :-
    myArray.push({myRef: 1, myValue: "W"});
    I can sort the array in numerical order using :-
    myArray.sortOn("myRef", Array.NUMERIC);
    but after sorting I would like to collapse the array using something along the lines of :-
    myArray.join("");
    to join the OTHER variable (myValue)...
    Is it possible to do this without pushing every instance of 'myValue' to another array and then joining that ?
    Many Thanks in advance
    Martin

    Hi kglad,
    I really appreciate you helping, but I have had to completely change my approach to this problem, therefore I will be marking the question as answered !!
    Thanks again

  • Sorting an array of objects by an attribute

    I'm pretty new to java so don't laugh if you think my question is real easy!
    I have an array of objects and I want to sort them according to an integer value stored in each object. Any help would be very much appreciated.
    Thanks for looking!!

    Perhaps an example would help:
    public class Person {
      private String name;
      private int age;
      public void setName(String name) { this.name = name; }
      public void setAge(int age) { this.age = age; }
      public String getName() { return name; }
      public int getAge() { return age; }
    =====
    public class PersonAgeSorter implements Comparable {
      public int compare(Object o1, Object o2) {
        Person p1 = (Person) o1;
        Person p2 = (Person) o2;
        Integer i1 = new Integer(p1.getAge());
        Integer i2 = new Integer(p2.getAge());
        return i1.compareTo(i2);
    =====
    public class PersonNameSorter implements Comparable {
      public int compare(Object o1, Object o2) {
        Person p1 = (Person) o1;
        Person p2 = (Person) o2;
        String s1 = p1.getName();
        String s2 = p2.getName();
        return s1.compareTo(s2);
    =====
    import java.util.Arrays;
    public class SortExample {
      public static void main(String [] args) {
      Person p1 = new Person();
      Person p2 = new Person();
      p1.setName("Tom");
      p1.setAge(22);
      p2.setName("Nancy");
      p2.setAge(33);
      Person [] people = new Person[2];
      people[0] = p1;
      people[1] = p2;
      Arrays.sort(people, new PersonAgeSorter());
      Arrays.sort(people, new PersonNameSorter());
    }

  • Help sorting an array of objects needed please.

    I am trying to sort the array Students[] in descending order of Fees due. Using the code below I get a null pointer error at runtime. The array is not completely full, it has 20 cells, but the variable studentArrayCounter holds the number of used cells. The 'getFeesDue()' code returns an integer value.
    Any help is appreciated.
         // Sort Student Records Method
               public void sortStudentRecords()
                int loopCount = 0;
               for (loopCount = 1; loopCount < studentArrayCounter; loopCount ++)
              if(Students[loopCount].getFeesDue()>Students[loopCount-1].getFeesDue())
                   SortStudents[0]=Students[loopCount-1];
                   Students[loopCount-1]=Students[loopCount];
                   Students[loopCount]=SortStudents[0];
         }

    Also, unless the excersize is to write a sort algorigthm (which I kinda doubt) you should use Arrays.sort
    Arrays.sort(Students, new Comparator() {
      public int compare(Object o1, Object o2) {
        Student s1 = (Student) o1;
        Student s2 = (Student) o2;
        return s1.getFeesDue() - s2.getFeesDue();
    });

  • Java sorting the array of objects

    Hi ,
    I have a question on sorting objects in java.
    I have a java interface some thing like :
    public classmyObj extends Nullable
        private int objId;
        private Datemydate;
        public int getObjID();
        public Date getmyDate();
        public int getISecondD();
      }I need to create the array of the objects of this class that are sorted on the ObjID:
    classmyObj[] collectionObjects
    I need to pass this collectionObjects to another function.
    Now how should I sort these objects based on the ObjID on collection?
    Please help with this!
    Thanks

    neeto wrote:
    Hi ,
    I have a question on sorting objects in java.
    I have a java interface some thing like :You mean class?
    >
    public classmyObj extends Nullable
    private int objId;
    private Datemydate;
    public int getObjID();
    public Date getmyDate();
    public int getISecondD();
    }I need to create the array of the objects of this class that are sorted on the ObjID:
    classmyObj[] collectionObjects
    I need to pass this collectionObjects to another function.
    Now how should I sort these objects based on the ObjID on collection?Create a comparator and use it in a call to Collections.sort (or Arrays.sort if you have an array)

  • Sorting an array of Objects based on a variable inside each object

    I have a class public class handInfo
              //VARS
                   int highC = 0;
                   int hVal = 0;
                   int numHand = 0;
              //CONSTRUCOTRS
                   public handInfo()
              //METHODS
                   public void setHC(int hc)
                             highC = hc;
                   public void setHV(int hv)
                             hVal = hv;
                   public void setNH(int nh)
                             numHand = nh;
                   public int getHC()
                             return highC;
                   public int getHV()
                             return hVal;
                   public int getNH()
                             return numHand;
         }now i have an array, handInfo[] hands = new handInfo[4];
                        hands[0] = new handInfo();
                        hands[0].setHC(HV);
                        hands[0].setNH(1);
                        hands[0].setHV(Val);
                        hands[1] = new handInfo();
                        hands[1].setHC(HV2);
                        hands[1].setNH(2);
                        hands[1].setHV(Val2);
                        hands[2] = new handInfo();
                        hands[2].setHC(HV3);
                        hands[2].setNH(3);
                        hands[2].setHV(Val3);
                        hands[3] = new handInfo();
                        hands[3].setHC(HV4);
                        hands[3].setNH(4);
                        hands[3].setHV(Val4);i need to know how to sort this array, based off hVal...
    D:

    Write a Comparator and call Arrays.sort(array, Comparator).

  • How to Sort Array of Object

    Hallo. I have an array of objects. Each object has id and name. How can i sort by name or by id??
    Thx for all
    Max

    array.sortOn("name");

  • Creating an array of objects of a class known ONLY at RUNTIME

    I have a method in a class which expects an array of objects of particular type (say A) as its only argument. I 'invoke' this method using reflection. I have the instances of the class A stored in a Vector. When I do 'toArray' on this vector, what I get back is an array of Objects and not an array of objects of A. I assign this array to the zeroth element of another Object array and pass that array as a second argument to the 'invoke' method. Of course, it throws an Exception saying - argument types mismatch. Because I am sending an array of Objects to a method expecting an array of objects of A. My problem is I don't know A until runtime. So I have to handle whatever I am getting back after doing 'toArray' on a vector as a Generic Object. I know there's another version of 'toArray' in the Vector class. But it's API documentation didn't help a lot.
    Can anybody please help me solve this problem? Any sort of hints/code snippet would be of great help.
    Does the above description makes any sense? If not, please let me know. I would try to illustrate it with a code sample.
    Thanks a lot in advance.

    Sorry, for the small typo. It is -
    clazz[] arr = (clazz [])java.lang.reflect.Array.newInstance(clazz, n);
    instead
    Thanks for the reply. I could do this. But I am
    getting a handle to the method to be 'invoke'd by
    looking at the types of the parameters its
    expecting(getParameterTypes). So I can't change it to
    accept an array of Generic Objects.
    I looked at the java.lang.reflect.Array class to do
    this. This is what I am trying to do-
    String variableName is an input coming into my
    program.
    n is the size of the array I'm trying to create.
    Class clazz = Class.forName(variableName);
    clazz[] arr = (clazz
    [])java.lang.reflect.newInstance(clazz, n);
    According to Reflection API, it should work, right?
    But compiler yells at me saying 'class clazz not
    found'.
    Any suggestions/hints/help?
    Thanks, again.

  • Trouble creating and populating an array of objects.

    I'm trying to create/populate an array of objects with consisting of a {string, double, integer}, and am having trouble getting this theory to work in Java. Any assistance provided would be greatly appreciated. Following are the two small progs:
    public class HairSalon
    { private String svcDesc; private double price; private int minutes;
    //Create a constructor to initialize data members
    HairSalon( )
    svcDesc = " "; price = 0.00; minutes = 0;
    //Create a constructor to receive data
         HairSalon(String s, double p, int m)
         svcDesc = s; price = p; minutes = m;
    //Create methods to get the data members
    public String getSvcDesc( )
         return svcDesc;
    public double getPrice( )
         return price;
    public int getMinutes( )
         return minutes;
    public class SortSalon
         public static void main(String[ ] args)
         SortSalon [] sal = new SortSalon[6];
    //Construct 6 SortSalon objects
              for (int i = 0; i < sal.length; i++)
              sal[i] = new SortSalon();
    //Add data to the 6 SortSalon objects
         sal[0] = new SortSalon("Cut"; 10.00, 10);
         sal[1] = new SortSalon("Shampoo", 5.00, 5);           sal[2] = new SortSalon("Sytle", 20.00, 20);
         sal[3] = new SortSalon("Manicure", 15.00, 15);
         sal[4] = new SortSalon("Works", 30.00, 30);
         sal[5] = new SortSalon("Blow Dry", 3.00, 3);
    //Display data for the 6 SortSalon Objects
         for (int i = 0; i < 6 ; i++ )
         { System.out.println(sal[i].getSvcDesc( ) + " " + sal.getPrice( ) + " " + sal[i].getMinutes( ));
         System.out.println("End of Report");

    Hey JavaMan5,
    That did do the trick! Thanks for the assistance. I was able to compile and run the program after adding my sorting routine. Do you happen to see anything I can do to clean it up further, or does it look ok? Thanks again,
    Ironjay69
    public class SortSalon
         public static void main(String[ ] args) throws Exception
         HairSalon [] sal = new HairSalon[6];      
         char selection;
    //Add data to the 6 HairSalon objects
         sal[0] = new HairSalon("Cut", 10.00, 10);
         sal[1] = new HairSalon("Shampoo", 5.00, 11);      
         sal[2] = new HairSalon("Sytle", 20.00, 20);
         sal[3] = new HairSalon("Manicure", 15.00, 25);
         sal[4] = new HairSalon("Works", 30.00, 30);
         sal[5] = new HairSalon("Blow Dry", 3.00, 3);
    System.out.println("How would you like to sort the list?");
         System.out.println("A by Price,");
         System.out.println("B by Time,");
         System.out.println("C by Description.");
         System.out.println("Please enter a code A, B or C, and then hit <enter>");
              selection = (char)System.in.read();
    //Bubble Sort the Array by user selection
              switch(selection)
              case 'A':
              BubbleSortPrice(sal, sal.length);
                   break;
                   case 'a':
              BubbleSortPrice(sal, sal.length);
                   break;
                   case 'B':
              BubbleSortTime(sal, sal.length);                    break;
                   case 'b':
              BubbleSortTime(sal, sal.length);
                   break;
                   case 'C':
              BubbleSortService(sal, sal.length);
                   break;
                   case 'c':
              BubbleSortService(sal, sal.length);
                   break;
                   default:
              System.out.println("Invalid Selection, Randomly Sorted List!");
    //Display data for the 6 HairSalon Objects
              for (int i = 0; i < sal.length ; i++ )
         System.out.println(sal.getSvcDesc( ) + " " + sal[i].getPrice( ) + " " + sal[i].getMinutes( ));
              System.out.println("___________");
              System.out.println("End of Report");
    public static void BubbleSortPrice(HairSalon[] array, int len)
    // Sorts the items in an array into ascending order by price
    int a, b;
    HairSalon temp;
    int highSubscript = len - 1;
    for(a = 0; a < highSubscript; ++a)
         for(b= 0; b < highSubscript; ++b)
         if(array.getPrice() > array[b + 1].getPrice())
              temp = array[b];
              array[b] = array [b + 1];
              array[b + 1] = temp;
    public static void BubbleSortTime(HairSalon[] array, int len)
    // Sorts the items in an array into ascending order by time
         int a, b;
         HairSalon temp;
         int highSubscript = len - 1;
         for(a = 0; a < highSubscript; ++a)
              for(b= 0; b < highSubscript; ++b)
         if(array[b].getMinutes() > array[b + 1].getMinutes())
         temp = array[b];
         array[b] = array [b + 1];
         array[b + 1] = temp;
    public static void BubbleSortService(HairSalon[] array, int len)
    // Sorts the items in an array into ascending order by time
         int a, b;
         HairSalon temp;
         int highSubscript = len - 1;
         for(a = 0; a < highSubscript; ++a)
         for(b= 0; b < highSubscript; ++b)
         if(array[b].getSvcDesc().compareTo( array[b + 1].getSvcDesc()) > 0)
                   temp = array[b];
                   array[b] = array [b + 1];
                   array[b + 1] = temp;

  • Renumber an Array of Object

    How would I renumber a property in an array of Object?
    For instance, say I have 5 Projects each with it's own corresponding priority property. Say I want to change the priority of the 5th Project to have a priority of 1. Meaning that the orginial 1 -4 projects would be pushed down and their proirities changed accordingly. Is there an API out there that does this?
    Thanks!
    Pete

    Not sure of the API but a possible solution is to sort the object array by that particular object property at the time of its creation. Later when you change the property you can use the same method that traverses the array again and re-arranges the objects based on new priorities.
    I agree this won't the most efficient solution but i'm sure you should be able to optimize it to some extent. :)
    Hope it helps.
    -ts

  • Sort an array

    how can i sort an array by name and also by size
    size is an int
    name a string
    whats the best way
    thankyou.

    Thats my main class code...
    as you can see i havent been able to work out the last few options on the menu
    which include size and name
    if anyone can get me started in the right direction id apreciate it very much thankyou!
    import java.util.*;
    import java.io.*;
    * @author aRiFy
    public class SpaceProgram {
    static int TotalObjects = 0;
    static Scanner sc = new Scanner(System.in);
    public static void main(String args[]) throws FileNotFoundException, IOException
    menuApp();
    //MENU
    public static void menuApp() throws FileNotFoundException, IOException
    SpaceObject[] Universe = new SpaceObject[1000000];
    System.out.println("Welcome to the Universe Program\n\n");
    char opt = 'x';
    while (opt !='M')
    System.out.println(""
    + "A - load from file\n"
    + "B - Display to screen\n"
    + "C - add a new space body\n"
    + "D - Write to file\n"
    + "E - Display by size\n"
    + "F - Display by name\n"
    + "G - Display moons of planet/dwarf planet\n"
    + "H - Display all space bodies in temperature range\n"
    + "I - Display a given space body\n"
    + "J - Display largest space body\n"
    + "K - Display smallest space body\n"
    + "L - Display most distant object\n"
    + "M - Exit Program\n");  
    System.out.print("Enter your Menu option: ");
    String s = sc.next();
    opt = s.charAt(0);
    switch (opt)
        case 'A':
        case 'a':
    input(Universe);
    break;
        case 'B':
        case'b':
    displayToScreen(Universe);
    break;
        case 'C':
        case 'c':
    addObject(Universe);
    break;
        case 'D':
        case'd':
    addObjectToFile(Universe);
    break;
        case 'E':
        case'e':
    sortSize(Universe);
    break;
        case 'F':
        case'f':
    sortName(Universe);
    break;
        case 'G':
        case'g':
    break;
        case 'H':
        case'h':
    tempRange(Universe);
    break;
        case 'I':
        case'i':
    SearchObjects(Universe);
    break;
        case 'J':
        case'j':
    findLargest(Universe);
    break;
        case 'K':
        case'k':
    findSmallest(Universe);
    break;
        case 'L':
        case'l':
    //mostDistant(Universe);
    break;
        case 'M':
        case'm':
    System.exit(0);
    break;
    default:
    //msg = "";//wrongValue();
    break;
    //ENDMENU
    //Add Space Object To File
    public static SpaceObject[] addObjectToFile(SpaceObject[] Universe ) throws FileNotFoundException, IOException
    System.out.println("What is the name of the text file you would like to write to? ");
    String textfile = sc.next();
    File f =new File(textfile);
    if(!f.exists())
    f.createNewFile();
    System.out.println("File Created");
    System.out.print("Add a Star, Planet, Dwarfplanet or Moon? "); //Asks to add
    String adding = sc.next();
    if (adding.equalsIgnoreCase("star")) //Add Star
    String OType="Star";
    System.out.println("Enter the name of the Star: ");
    String OName = sc.next();
    System.out.println("Enter the Radius: ");
    String ORadius = sc.next();
    double ORadiusD=Double.parseDouble(ORadius);
    System.out.println("Class O -blue");
    System.out.println("Class B -blue white");
    System.out.println("Class A -white");
    System.out.println("Class F -yellowish white");
    System.out.println("Class G -yellow");
    System.out.println("Class K -orange");
    System.out.println("Class M -red");
    System.out.println("Class W -superluminous blue");
    System.out.println("Class L -dark red");
    System.out.println("Class T -cool brown dwarf");
    System.out.println("Class Y -ultra cool brown dwarf");
    System.out.println("Class C -carbom star");
    System.out.println("Class S -between a class M and carbon star");
    System.out.println("Class D -white dwarf");
    System.out.println("Enter A Spectral Type: ");
    String ST = sc.next();
    System.out.println("I   -supergiants");
    System.out.println("II  -bright giants");
    System.out.println("III -normal giants");
    System.out.println("IV  -subgiants");
    System.out.println("V   -dwarfs");
    System.out.println("VI  -subdwarfs");
    System.out.println("VII -white dwarfs");
    System.out.println("Enter Yerkes Spectral Classification: ");
    String YSC = sc.next();
    System.out.println("Enter the Distance: ");
    String Distance = sc.next();
    double DistanceD=Double.parseDouble(Distance);
    Universe[TotalObjects]= new Star(OType, OName, ORadiusD, ST, YSC, DistanceD);
    Universe[TotalObjects].display();
    TotalObjects = TotalObjects +1;
    System.out.println("Star Added");  
    PrintWriter outputStream = null;
    try
        outputStream = new PrintWriter(new FileOutputStream(textfile, true));
    catch(FileNotFoundException e)
        System.out.println("Error opening spacebodies.txt");
        System.exit(0);
    System.out.println("Writing to file");
    outputStream.println(OType);
    outputStream.println(OName);
    outputStream.println(ORadiusD);
    outputStream.println(ST);
    outputStream.println(YSC);
    outputStream.println(DistanceD);
    outputStream.println("\n");
    outputStream.close();
    System.out.println("Written to file succesfully");
    else if (adding.equalsIgnoreCase("planet")) //Add Planet
    String OType="Planet";
    System.out.println("Enter the name of the Planet: ");
    String OName = sc.next();
    System.out.println("Enter the Radius: ");
    String ORadius = sc.next();
    double ORadiusD=Double.parseDouble(ORadius);
    System.out.println("Enter the Mass: ");
    String PMass = sc.next();
    System.out.println("Enter the Orbital Period: ");
    String POB = sc.next();
    double POBD=Double.parseDouble(POB);
    System.out.println("Enter the Temperature: ");
    String PTemp = sc.next();
    double PTempD=Double.parseDouble(PTemp);
    Universe[TotalObjects]= new Planet(OType, OName, ORadiusD, PMass, POBD, PTempD);
    Universe[TotalObjects].display();
    TotalObjects = TotalObjects +1;
    System.out.println("Planet Added");
    PrintWriter outputStream = null;
    try
        outputStream = new PrintWriter(new FileOutputStream(textfile, true));
    catch(FileNotFoundException e)
        System.out.println("Error opening spacebodies.txt");
        System.exit(0);
    System.out.println("Writing to file");
    outputStream.println(OType);
    outputStream.println(OName);
    outputStream.println(ORadiusD);
    outputStream.println(PMass);
    outputStream.println(POB);
    outputStream.println(PTempD);
    outputStream.println("\n");
    outputStream.close();
    System.out.println("Written to file succesfully");
    else if (adding.equalsIgnoreCase("dwarfplanet"))    //add dwarfplanet
    String OType="DwarfPlanet";
    System.out.println("Enter the name of the Dwarf Planet: ");
    String OName = sc.next();
    System.out.println("Enter the Radius: ");
    String ORadius = sc.next();
    double ORadiusD=Double.parseDouble(ORadius);
    System.out.println("Enter the Mass: ");
    String PMass = sc.next();
    System.out.println("Enter the Temperature: ");
    String PTemp = sc.next();
    double PTempD=Double.parseDouble(PTemp);
    Universe[TotalObjects]= new DwarfPlanet(OType, OName, ORadiusD, PMass, PTempD);
    Universe[TotalObjects].display();
    TotalObjects = TotalObjects +1;
    System.out.println("DwarfPlanet Added");
    PrintWriter outputStream = null;
    try
        outputStream = new PrintWriter(new FileOutputStream(textfile, true));
    catch(FileNotFoundException e)
        System.out.println("Error opening spacebodies.txt");
        System.exit(0);
    System.out.println("Writing to file");
    outputStream.println(OType);
    outputStream.println(OName);
    outputStream.println(ORadiusD);
    outputStream.println(PMass);
    outputStream.println(PTempD);
    outputStream.println("\n");
    outputStream.close();
    System.out.println("Written to file succesfully");
    else if (adding.equalsIgnoreCase("moon"))
    String OType="Moon";
    System.out.println("Enter the name of the Moon: ");
    String OName = sc.next();
    System.out.println("Enter the Radius: ");
    String ORadius = sc.next();
    double ORadiusD=Double.parseDouble(ORadius);
    System.out.println("Enter the Mass: ");
    String MMass = sc.next();
    System.out.println("Enter the Planet: ");
    String Planet = sc.next();
    System.out.println("Enter the Temperature: ");
    String MTemp = sc.next();
    double MTempD=Double.parseDouble(MTemp);
    Universe[TotalObjects]= new Moon(OType, OName, ORadiusD, MMass, Planet, MTempD);
    Universe[TotalObjects].display();
    TotalObjects = TotalObjects +1;
    System.out.println("Moon Added");
    PrintWriter outputStream = null;
    try
        outputStream = new PrintWriter(new FileOutputStream(textfile, true));
    catch(FileNotFoundException e)
        System.out.println("Error opening spacebodies.txt");
        System.exit(0);
    System.out.println("Writing to file");
    outputStream.println(OType);
    outputStream.println(OName);
    outputStream.println(ORadiusD);
    outputStream.println(MMass);
    outputStream.println(Planet);
    outputStream.println(MTempD);
    outputStream.println("\n");
    outputStream.close();
    System.out.println("Written to file succesfully");
    else
    System.out.println("You have entered an invalid input please try again");//invalid input
    addObjectToFile(Universe);
    return Universe;
    public static SpaceObject[] addObject(SpaceObject[] Universe ) throws FileNotFoundException
    System.out.print("Add a Star, Planet, Dwarfplanet or Moon? "); //Asks to add
    String adding = sc.next();
    if (adding.equalsIgnoreCase("star")) //Add Star
    String OType="Star";
    System.out.println("Enter the name of the Star: ");
    String OName = sc.next();
    System.out.println("Enter the Radius: ");
    String ORadius = sc.next();
    double ORadiusD=Double.parseDouble(ORadius);
    System.out.println("Class O -blue");
    System.out.println("Class B -blue white");
    System.out.println("Class A -white");
    System.out.println("Class F -yellowish white");
    System.out.println("Class G -yellow");
    System.out.println("Class K -orange");
    System.out.println("Class M -red");
    System.out.println("Class W -superluminous blue");
    System.out.println("Class L -dark red");
    System.out.println("Class T -cool brown dwarf");
    System.out.println("Class Y -ultra cool brown dwarf");
    System.out.println("Class C -carbom star");
    System.out.println("Class S -between a class M and carbon star");
    System.out.println("Class D -white dwarf");
    System.out.println("Enter A Spectral Type: ");
    String ST = sc.next();
    //char STc = ST.charAt(0);
    System.out.println("I   -supergiants");
    System.out.println("II  -bright giants");
    System.out.println("III -normal giants");
    System.out.println("IV  -subgiants");
    System.out.println("V   -dwarfs");
    System.out.println("VI  -subdwarfs");
    System.out.println("VII -white dwarfs");
    System.out.println("Enter Yerkes Spectral Classification: ");
    String YSC = sc.next();
    System.out.println("Enter the Distance: ");
    String Distance = sc.next();
    double DistanceD=Double.parseDouble(Distance);
    Universe[TotalObjects]= new Star(OType, OName, ORadiusD, ST, YSC, DistanceD);
    Universe[TotalObjects].display();
    TotalObjects = TotalObjects +1;
    System.out.println("Star Added");  
    else if (adding.equalsIgnoreCase("planet")) //Add Planet
    String OType="Planet";
    System.out.println("Enter the name of the Planet: ");
    String OName = sc.next();
    System.out.println("Enter the Radius: ");
    String ORadius = sc.next();
    double ORadiusD=Double.parseDouble(ORadius);
    System.out.println("Enter the Mass: ");
    String PMass = sc.next();
    System.out.println("Enter the Orbital Period: ");
    String POB = sc.next();
    double POBD=Double.parseDouble(POB);
    System.out.println("Enter the Temperature: ");
    String PTemp = sc.next();
    double PTempD=Double.parseDouble(PTemp);
    Universe[TotalObjects]= new Planet(OType, OName, ORadiusD, PMass, POBD, PTempD);
    Universe[TotalObjects].display();
    TotalObjects = TotalObjects +1;
    System.out.println("Planet Added");
    else if (adding.equalsIgnoreCase("dwarfplanet"))    //add dwarfplanet
    String OType="DwarfPlanet";
    System.out.println("Enter the name of the Dwarf Planet: ");
    String OName = sc.next();
    System.out.println("Enter the Radius: ");
    String ORadius = sc.next();
    double ORadiusD=Double.parseDouble(ORadius);
    System.out.println("Enter the Mass: ");
    String PMass = sc.next();
    System.out.println("Enter the Temperature: ");
    String PTemp = sc.next();
    double PTempD=Double.parseDouble(PTemp);
    Universe[TotalObjects]= new DwarfPlanet(OType, OName, ORadiusD, PMass, PTempD);
    Universe[TotalObjects].display();
    TotalObjects = TotalObjects +1;
    System.out.println("DwarfPlanet Added");
    else if (adding.equalsIgnoreCase("moon"))
    String OType="Moon";
    System.out.println("Enter the name of the Moon: ");
    String OName = sc.next();
    System.out.println("Enter the Radius: ");
    String ORadius = sc.next();
    double ORadiusD=Double.parseDouble(ORadius);
    System.out.println("Enter the Mass: ");
    String MMass = sc.next();
    System.out.println("Enter the Planet: ");
    String Planet = sc.next();
    System.out.println("Enter the Temperature: ");
    String MTemp = sc.next();
    double MTempD=Double.parseDouble(MTemp);
    Universe[TotalObjects]= new Moon(OType, OName, ORadiusD, MMass, Planet, MTempD);
    Universe[TotalObjects].display();
    TotalObjects = TotalObjects +1;
    System.out.println("Moon Added");
    else
    System.out.println("You have entered an invalid input please try again");//invalid input
    addObject(Universe);
    return Universe;
    //read text file
    public static void input(SpaceObject[] Universe) throws FileNotFoundException
        System.out.println("What is the name of the text file you would like to write to? ");
    String textfile = sc.next();
    File f =new File(textfile);
        Scanner infile;
        infile = new Scanner(new File("spacebodies.txt"));
        while (infile.hasNext())
            String SpaceType = infile.next();
            String OType = infile.nextLine();
            String OName = infile.nextLine();
            double ORadius = infile.nextDouble();
            if (SpaceType.equals("Star"))
                String ST = infile.next();
                String YSC = infile.next();
                infile.nextLine();
                double Distance = infile.nextDouble();
                Universe[TotalObjects]= new Star("Star", OName, ORadius, ST, YSC, Distance);
                Universe[TotalObjects].display();
                TotalObjects = TotalObjects +1;
                System.out.println(""); 
            else if (SpaceType.equals("Planet"))
                String PMass = infile.next();
                infile.nextLine();
                double POB = infile.nextDouble();
                double PTemp = infile.nextDouble();
                Universe[TotalObjects]= new Planet("Planet", OName, ORadius, PMass, POB, PTemp);
                Universe[TotalObjects].display();
                TotalObjects = TotalObjects +1;
                System.out.println(""); 
                    else if (SpaceType.equals("DwarfPlanet"))
                String PMass = infile.next();
                infile.nextLine();
                double PTemp = infile.nextDouble();
                Universe[TotalObjects]= new DwarfPlanet("DwarfPlanet", OName, ORadius, PMass, PTemp);
                Universe[TotalObjects].display();
                TotalObjects = TotalObjects +1;
                System.out.println(""); 
                    else if (SpaceType.equals("Moon"))
                String MMass = infile.next();
                String Planet = infile.nextLine();
                infile.nextLine();
                double MTemp = infile.nextDouble();
                Universe[TotalObjects]= new Moon("Moon", OName, ORadius, MMass, Planet, MTemp);
                Universe[TotalObjects].display();
                TotalObjects = TotalObjects +1;
                System.out.println(""); 
            else{
                System.out.println("Error");
    //Display To Screen
    public static void displayToScreen(SpaceObject[] Universe)
    System.out.println("Displaying Added Space Objects\n");
    if (TotalObjects>0)
    for (int i=0;i<TotalObjects;i++)
    Universe.display();
    System.out.println("");
    //Search Objects
    public static void SearchObjects(SpaceObject[] Universe)
    System.out.println("Please Enter a Space Body to Search: ");
    String SBody = sc.nextLine();
    SBody = sc.nextLine();
    for (int i=0;i<TotalObjects;i++)
    if (Universe[i].OName.equalsIgnoreCase(SBody))
    Universe[i].display();
    //Find Largetst
    public static void findLargest(SpaceObject[] Universe)
    double MaxRadius = Universe[0].ORadius;
    int Max=0;
    for (int i=0;i<TotalObjects;i++)
    if (MaxRadius < Universe[i].ORadius)
    MaxRadius = Universe[i].ORadius;
    Max = i;
    Universe[Max].display();
    //Find Smallest
    public static void findSmallest(SpaceObject[] Universe)
    double MaxRadius = 900000;
    int Max=0;
    for (int i=0;i<TotalObjects;i++)
    if (MaxRadius < Universe[i].ORadius)
    MaxRadius = Universe[i].ORadius;
    Max = i;
    Universe[Max].display();
    //Temp Range
    public static void tempRange(SpaceObject[] Universe)
    public static void mostDistant(SpaceObject[] Universe)
    public static void sortSize(SpaceObject[] Universe)
    public static void sortName(SpaceObject[] Universe)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Sort an ArrayCollection of Objects

    I have an ArrayCollection where I'm storing Objects. These
    Objects have properties set like:
    var aurNode:Object = new Object();
    aurNode.categoryName = value.@name;
    aurNode.total = value.@totalSales;
    I want to sort this ArrayCollection by Object.total . How can
    I do this? I was looking through a page here:
    http://blog.flexexamples.com/2007/08/05/sorting-an-arraycollection-using-the-sortfield-and -sort-classes/
    but I couldn't get it to work in my situation correctly. Does
    anyone have any suggestions?
    Thanks!

    I've written a test example of how you can add / remove a
    sort to an identifier on an array collection. Hope this helps.
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute" creationComplete="initComplete()">
    <mx:Script>
    <![CDATA[
    import mx.collections.Sort;
    import mx.collections.SortField;
    import mx.collections.ArrayCollection;
    private var sortage:Sort;
    [Bindable] private var phpData:ArrayCollection = new
    ArrayCollection();
    private function initComplete():void {
    for(var i:Number = 0; i < 20; i++){
    phpData.addItem({label:"item"+i, total:(i%2) + 100,
    isSelected:(i%2) ? true : false});
    private function sortCollection(collection:ArrayCollection,
    field:String, numeric:Boolean):void {
    // => Sort Collection
    sortage = new Sort();
    sortage.fields = [new SortField(field, false, false,
    numeric)];
    collection.sort = sortage;
    collection.refresh();
    private function removeSort(collection:ArrayCollection):void
    // => Remove Sort
    sortage = new Sort();
    sortage.fields = [new SortField(null, false, false, false)];
    collection.sort = sortage;
    collection.refresh();
    ]]>
    </mx:Script>
    <mx:Button x="10" y="10" label="Create Sort"
    click="sortCollection(phpData, 'total', true)"/>
    <mx:Button x="120" y="10" label="Remove Sort"
    click="removeSort(phpData)"/>
    <mx:DataGrid left="10" right="10" y="40"
    dataProvider="{phpData}">
    <mx:columns>
    <mx:DataGridColumn headerText="Title"
    dataField="label"/>
    <mx:DataGridColumn headerText="Total"
    dataField="total"/>
    <mx:DataGridColumn headerText="Included"
    dataField="isSelected"/>
    </mx:columns>
    </mx:DataGrid>
    </mx:Application>

  • Sort String Array by Date

    I use the following code to populate a string array:
    File dirFile          = new File("C:\\somedir");
    String fileImport[]      = dirFile.list();
    This gives me a string array with a whole bunch of files in the following format:
    XXXDDMMYYHHMISS.xml
    What I need to know is what is the easiest way to sort this array based on this date format, or any date format, in the ascending order, so that when I am loading my XML files, I get the oldest one first.
    Appreciate any input.
    Sam

    Use the String name of the file (the Date part), together with a java.text.SimpleDateFormat object to parse() the String. You have to set the formatter with a pattern - these are explained fully in the Javadocs for the SimpleDateFormat class. After parsing, you will have java.util.Date objects for each of the files - you can then use these as keys in a java.util.SortedMap (the values would be the files) - the natural ordering of dates will ensure that they are ordered appropriately

  • Sorting an array based on the value of another array

    Hi
    Ive got 2 arrys... An Integer[]{11,12,23,24,25};
    and another one double[]{60,79,83,54,67};
    i wanna sort the first array based on the values of the second array..
    ie my result should be double[]{83,79,67,60,54} and
    Integer[]={23,12,25,11,24}...........
    is thr any easy method to do tis..

    You should make a class with the int and the double as fields; and have your class implement Comparable to compare on the double the way you want; and just have an array of objects of this class, and sort it.
    Because the corresponding elements in your arrays are essentially linked, so they should be together.
    Edited by: spoon_ on Apr 12, 2008 2:17 AM

Maybe you are looking for

  • Importing data from one table to another in the same schema

    I know this possibly very simple, but I can't seem to figure it out. I have two tables; one with live user data and another, identical except name, with archive data. I want to export data that has been flagged from table 1 and archive it by importin

  • Having to reorder twice and waiting a month to fin...

    I ordered BT Broadband with BT about a month and a half ago (the first order)! I asked for a new line(not the exsisting line) i placed the online order and set everything up happy days or so i thought!!! new internet very soon. A few days later my br

  • Remote Desktop Connection - viewing screen

    Hi, I just installed Remote Desktop Connection on my Imac at home so I can access my work PC. Everything works fine but my image I view is only about 5" x 6". It seems like a waste of the 27" screen. Does anyone know how I can increase the size of th

  • How to disable any record in a Tabular Data Block

    Hi, I have a tabular data block having 10 records, every record has a check box(1 check box on each row). I want to disable all items in that particular record where user checks the check box(check box is UNCHECKED by default). Is this possible in WH

  • Logical translation of nested logic:equal tags ?

    I see this in a JSP (I've simplified it) that I have to modify: <logic:notEqual name="someForm" property="XYZ" value="4"> <logic:notEqual name="someForm" property="XYZ" value="5"> <logic:notEqual name="someForm" property="XYZ" value="5"> <TD>String 1