8 Replies - 1917 Views - Last Post: 01 March 2010 - 08:59 AM Rate Topic: -----

#1 Guest_ola*


Reputation:

sorting array

Posted 01 March 2010 - 05:46 AM

how do i sort the following array in order of lastname, followed by first name?
below is aw far av gone......



package person;

import java.util.Arrays;

/**
 *
 * @author student
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
{


Person[] staff = new Person[8];

        staff[0] = new Student("Allen", "King", 2004, 5);
        staff[1] = new Student("Joseph", "Keane", 2004, 4);
        staff[2] = new Employee("joe", "King", 2002, "full-time");
        staff[3] = new Employee("james", "King", 2005, "temporary");
        staff[4] = new Faculty("kate", "jakie", 2009,"part-time", "E104");
        staff[5] = new Faculty("Rita", "Rose", 2009,"full-time", "E107");
        staff[6] = new Admin("abel", "King", 2000,"temporary",  5);
        staff[7] = new Admin("cain", "fingles", 2001,"part-time",  5);


        for(int i = 0; i < staff.length; i++)
        {
            System.out.print(staff[i].makeEmail()+ "\n");
            // Java determines which makeEmail() method to use
            //because the other classes overrides the makeEmail() from the abstract Person
            // and the override methods allows java to use the
            //override method specofied in eash class.
        }


Arrays.sort(staff);
        for(int i = 0; i < staff.length; i++)
        {
            System.out.print(staff);
        }



}


This post has been edited by pbl: 01 March 2010 - 06:23 PM
Reason for edit:: Code tags fixed :code:


Is This A Good Question/Topic? 0

Replies To: sorting array

#2 Simple_Condolences  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 138
  • Joined: 10-January 10

Re: sorting array

Posted 01 March 2010 - 06:49 AM

So closeeeeee!

:code:

We would need to see all of your code to help you with your problem... But, from what I see... the general idea would be to loop through your array, pull the second element of each object(the last name) and then alphabetize. I can't remember if java offers this function but I used a basic coding language about a year ago that accepted > and < to compare where a letter was in the alphabet compared to another. Also, you'll want to use substring... so...

String str = "This is a string for using substrings!";
System.out.println(str.substring(0, 3));//would print 'This'
System.out.println(str.substring(3, 11));//would print 's in a str'



Basically, substring(x,y) takes the letter at the index x and stops at the letter index y.
Was This Post Helpful? 0
  • +
  • -

#3 Guest_OLA*


Reputation:

Re: sorting array

Posted 01 March 2010 - 07:46 AM

ok.....below is the full code......

<code>

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package person;


/**
*
* @author student
*/
public abstract class Person {


private String fName;
private String lName;
private int entryYear;

//DEFAULT CONSTRUCTOR

public Person()
{
this.fName = "David";
this.lName = "Green";
this.entryYear = 2007;

}

//CONSTRUCTOR WITH PARAMETERS

public Person(String newfirst, String newLast, int newYear )
{
this.fName = newfirst;
this.lName = newLast;
this.entryYear = newYear;

}



public String getFname()
{
return fName;
}

public void setFname(String newFname)
{
this.fName = newFname;
}

public String getLname()
{
return lName;
}

public void setLname(String newLname)
{
this.lName = newLname;
}

public int getYear()
{
return entryYear;
}

public void setYear(int newYear)
{
this.entryYear = newYear;
}

public String makeLogin()
{
StringBuffer login = new StringBuffer();

login.append(fName.charAt(0)); //first letter of fName

if (lName.length() == 2)
{
System.out.print("name too short for id" + "\n");// code debuggging
lName = lName + "XY";
}

login.append(lName.substring(0, 3));// first 3 letters of lname

// login.append(entryYear%100);
// last two digits of the year if the year is below 2001 i.e 1976, 1998, etc
// 6 % 4 = 2
//because 6 / 4 is 1, with the remains of 2
//so if we operate the % operator on the year and 100, we will get:
//1976 % 100 = 76
//1998 % 100 = 98
String sYear = Integer.toString(entryYear);
login.append(sYear.substring(2)); // last two digits of the year
return login.toString();

}



@Override
public boolean equals(Object o) {
Person p = (Person) o;

if( fName.equals(p.getFname()) && lName.equals(p.getLname()) && entryYear == p.getYear() )
return true;
else
return false;
}



// ABSTRACT METHOD

public abstract String makeEmail();

public abstract String makeEmail2();

}



STUDENT CLASS...............



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package person;



/**
*
* @author student
*/
public class Student extends Person {
private int credit;

//DEFAULT CONSTRUCTOR

public Student()
{
super();
this.credit = 0;
}

//CONSTRUCTOR WITH PARAMETERS

public Student(int newCredits)
{
super("David", "Green", 2007);
this.credit = newCredits;
}



//MAKE NEW STUDENT WITH SPECIFIED FNAME,LNAME AND ENTYRYEAR
public Student(String newFirst, String newLast, int newYear, int newCredits) {
super(newFirst, newLast, newYear);
this.credit = newCredits;
}


public double getCredit()
{
return credit;
}

public void setCredit( int cCredit )
{
credit = cCredit;
}

// APPEND METHOD
public String makeEmail()
{
StringBuffer email = new StringBuffer();
email.append(getFname());
email.append(".");
email.append(getLname());
email.append("@studentmail.dkit.ie");
return email.toString();
}

//CONCAT METHOD
public String makeEmail2()
{
String email = getFname() + "." + getLname() + "@studentmail.dkit.ie";
return email;
}


public int compareTo(Student other) {

if (credit < other.getCredit())
{
return -1;
}

if (credit < other.getCredit())
{
return 1;
}

// otherwise
return 0;

}


@Override
public boolean equals(Object k) {
Person w = (Person) k;

if( getFname().equals(w.getFname()))
return true;
else
return false;
}






}


EMPLOYEE CLASS...........



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package person;

/**
*
* @author oayoa08
*/
public class Employee extends Person implements Comparable <Employee> {
private String status;


public Employee()
{
super();
this.status = "part-time";
}

//CONSTRUCTOR WITH PARAMETERS

public Employee(String newStatus)
{
super("David", "Green", 2007);
this.status = newStatus;
}

//MAKE NEW EMPLOYEE WITH SPECIFIED FNAME,LNAME,ENTYRYEAR AND STATUS
public Employee(String newFirst, String newLast, int newYear, String newStatus) {
super(newFirst, newLast, newYear);
this.status = newStatus;
}

public String getStatus()
{

return status;
}

public void setStatus( String sStatus )
{
this.status = sStatus;
}

// APPEND METHOD
@Override
public String makeEmail() {
StringBuffer email = new StringBuffer();
email.append(getFname());
email.append(".");
email.append(getLname());
email.append("@dkit.ie");
return email.toString();
}
//CONCAT METHOD
public String makeEmail2()
{
String email = getFname() + "." + getLname() + "@dkit.ie";
return email;
}

@Override
public boolean equals(Object newOne)
{
Employee p = (Employee) newOne;

if(status.equals(p.getStatus()))
{
return true;
}else
{
return false;
}
}

public int compareTo(Employee o) {
if(getYear() < o.getYear())
{
return -1;
}
if(getYear() > o.getYear())
{
return 1;
}
//otherwise
return 0;
}










}


ADMIN CLASS.........


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package person;

/**
*
* @author oayoa08
*/
public class Admin extends Employee implements Comparable<Employee>{

private int grade;


public Admin()
{
super();
this.grade = 1 ;
}

//CONSTRUCTOR WITH PARAMETERS

public Admin(int newAdmin)
{
super("David", "Green", 2007, "part-time");
this.grade = newAdmin;
}

//MAKE NEW EMPLOYEE WITH SPECIFIED FNAME,LNAME,ENTYRYEAR AND STATUS
public Admin(String newFirst, String newLast, int newYear, String newStatus, int newAdmin) {
super(newFirst, newLast, newYear, newStatus);
this.grade = newAdmin;
}

public int getGrade()
{
if((grade < 1)|| (grade > 7))
{
System.out.print("The value specified is outside the grade range");

}
return grade;
}

public void setGrade(int newAdmin)
{
this.grade = newAdmin;
}

// APPEND METHOD
@Override
public String makeEmail() {
StringBuffer email = new StringBuffer();
email.append(getFname());
email.append(".");
email.append(getLname());
email.append("@admin_mail.dkit.ie");
return email.toString();
}

//CONCAT METHOD
@Override
public String makeEmail2 ()
{
String email = getFname() + "." + getLname() + "@dkit.ie";
return email;
}


public int compareTo(Admin other) {

if (grade < other.getGrade())
{
return -1;
}

if (grade < other.getGrade())
{
return 1;
}

// otherwise
return 0;

}


public boolean equals(Object v) {
Faculty s = (Faculty) v;

if( getStatus().equals(s.getStatus()))
return true;
else
return false;
}
}



FACULTY CLASS........



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package person;

/**
*
* @author oayoa08
*/
public class Faculty extends Employee implements Comparable <Employee>
{

private String office;


public Faculty()
{
super();
this.office = " ";
}

//CONSTRUCTOR WITH PARAMETERS

public Faculty(String newoffice)
{
super("David", "Green", 2007, "part-time");
this.office = newoffice;
}

//MAKE NEW EMPLOYEE WITH SPECIFIED FNAME,LNAME,ENTYRYEAR AND STATUS
public Faculty(String newFirst, String newLast, int newYear, String newStatus, String newOffice) {
super(newFirst, newLast, newYear, newStatus);
this.office = newOffice;
}

public String getOffice()
{

return office;
}

public void setOffice( String oOffice )
{
this.office = oOffice;
}
// APPEND METHOD
@Override
public String makeEmail() {
StringBuffer email = new StringBuffer();
email.append(getFname());
email.append(".");
email.append(getLname());
email.append("@staff_mail.dkit.ie");
return email.toString();
}

//CONCAT METHOD
@Override
public String makeEmail2 ()
{
String email = getFname() + "." + getLname() + "@dkit.ie";
return email;
}

public int compareTo(Faculty other) {

if (getYear() < other.getYear())
{
return -1;
}

if (getYear() < other.getYear())
{
return 1;
}

// otherwise
return 0;

}


@Override
public boolean equals(Object v) {
Faculty s = (Faculty) v;

if( office.equals(s.getOffice()))
return true;
else
return false;
}



}
MAIN METHOD...............




/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package person;

import java.util.Arrays;




/**
*
* @author student
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {


Person[] staff = new Person[8];

staff[0] = new Student("Allen", "King", 2004, 5);
staff[1] = new Student("Joseph", "Keane", 2004, 4);
staff[2] = new Employee("joe", "King", 2002, "full-time");
staff[3] = new Employee("james", "King", 2005, "temporary");
staff[4] = new Faculty("kate", "jakie", 2009,"part-time", "E104");
staff[5] = new Faculty("Rita", "Rose", 2009,"full-time", "E107");
staff[6] = new Admin("abel", "King", 2000,"temporary", 5);
staff[7] = new Admin("cain", "fingles", 2001,"part-time", 5);


for(int i = 0; i < staff.length; i++)
{
System.out.print(staff[i].makeEmail()+ "\n");
// Java determines which makeEmail() method to use
//because the other classes overrides the makeEmail() from the abstract Person
// and the override methods allows java to use the
//override method specofied in eash class.
}




Arrays.sort(staff);

// print out information about all Employee objects
for (int i = 0; i < staff.length; i++) {
Person e = staff[i];
// System.out.print(staff);
System.out.println("lastName=" + e.getFname() + ",First Name=" + e.getLname());
}

</code>




FORM MY MAIN METHOD...HOW DO I SORT THE ARRAY I CREATED IN MY MAIN METHOD IN ORDER OF LAST NAME , THEN FIRST NAME?
Was This Post Helpful? 0

#4 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10185
  • View blog
  • Posts: 37,603
  • Joined: 27-December 08

Re: sorting array

Posted 01 March 2010 - 07:58 AM

The code tags should use square brackets, not angle brackets as this is BBCode, not XML. Like so:
:code:

Also, you should make your Person class comparable by implementing Comparable<Person>. Then, implement the compareTo() method so that last name is compared first, then first name if the last names are equal. Then, you can just invoke the Arrays.sort() on your array. Like so:
class Person implements Comparable<Person>{
   private String first, last;
   
   public int compareTo(Person other){
       //if last == other.last, return comparison of first names
       if(this.last.compareTo(other.getLastName()) == 0)
          return this.first.compareTo(other.getFirstName());

       //otherwise, compare last names
       return this.last.compareTo(other.getLastName());
   }
}



@Simple_Condolences: Even if you use substring(), a String is returned, and Strings cannot be compared using the <, <=, >, or >= operators.
Was This Post Helpful? 0
  • +
  • -

#5 Guest_deterrent silkened*


Reputation:

Re: sorting array

Posted 01 March 2010 - 08:13 AM

by implementing Comparable<Person> in the person class....my program is giving me errors as the admin and faculty extends EMPLOYEE and also implements comaprable by overriding methods? what do i do?
Was This Post Helpful? 0

#6 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10185
  • View blog
  • Posts: 37,603
  • Joined: 27-December 08

Re: sorting array

Posted 01 March 2010 - 08:38 AM

Can you post your code? Also, are you Ola or is this another user? Remember to use code tags properly, like so:
:code:

Edit: Can you include the errors your compiler is giving you as well?

This post has been edited by macosxnerd101: 01 March 2010 - 08:38 AM

Was This Post Helpful? 0
  • +
  • -

#7 Guest_Guest*


Reputation:

Re: sorting array

Posted 01 March 2010 - 08:47 AM

yeah am same ola........lol
ok let do it dis way to avoid confusion....... below is the code......








/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package person;


/**
*
* @author student
*/
public abstract class Person {


private String fName;
private String lName;
private int entryYear;

//DEFAULT CONSTRUCTOR

public Person()
{
this.fName = "David";
this.lName = "Green";
this.entryYear = 2007;

}

//CONSTRUCTOR WITH PARAMETERS

public Person(String newfirst, String newLast, int newYear )
{
this.fName = newfirst;
this.lName = newLast;
this.entryYear = newYear;

}



public String getFname()
{
return fName;
}

public void setFname(String newFname)
{
this.fName = newFname;
}

public String getLname()
{
return lName;
}

public void setLname(String newLname)
{
this.lName = newLname;
}

public int getYear()
{
return entryYear;
}

public void setYear(int newYear)
{
this.entryYear = newYear;
}

public String makeLogin()
{
StringBuffer login = new StringBuffer();

login.append(fName.charAt(0)); //first letter of fName

if (lName.length() == 2)
{
System.out.print("name too short for id" + "\n");// code debuggging
lName = lName + "XY";
}

login.append(lName.substring(0, 3));// first 3 letters of lname

// login.append(entryYear%100);
// last two digits of the year if the year is below 2001 i.e 1976, 1998, etc
// 6 % 4 = 2
//because 6 / 4 is 1, with the remains of 2
//so if we operate the % operator on the year and 100, we will get:
//1976 % 100 = 76
//1998 % 100 = 98
String sYear = Integer.toString(entryYear);
login.append(sYear.substring(2)); // last two digits of the year
return login.toString();

}



@Override
public boolean equals(Object o) {
Person p = (Person) o;

if( fName.equals(p.getFname()) && lName.equals(p.getLname()) && entryYear == p.getYear() )
return true;
else
return false;
}



// ABSTRACT METHOD

public abstract String makeEmail();

public abstract String makeEmail2();

}



STUDENT CLASS...............



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package person;



/**
*
* @author student
*/
public class Student extends Person {
private int credit;

//DEFAULT CONSTRUCTOR

public Student()
{
super();
this.credit = 0;
}

//CONSTRUCTOR WITH PARAMETERS

public Student(int newCredits)
{
super("David", "Green", 2007);
this.credit = newCredits;
}



//MAKE NEW STUDENT WITH SPECIFIED FNAME,LNAME AND ENTYRYEAR
public Student(String newFirst, String newLast, int newYear, int newCredits) {
super(newFirst, newLast, newYear);
this.credit = newCredits;
}


public double getCredit()
{
return credit;
}

public void setCredit( int cCredit )
{
credit = cCredit;
}

// APPEND METHOD
public String makeEmail()
{
StringBuffer email = new StringBuffer();
email.append(getFname());
email.append(".");
email.append(getLname());
email.append("@studentmail.dkit.ie");
return email.toString();
}

//CONCAT METHOD
public String makeEmail2()
{
String email = getFname() + "." + getLname() + "@studentmail.dkit.ie";
return email;
}


public int compareTo(Student other) {

if (credit < other.getCredit())
{
return -1;
}

if (credit < other.getCredit())
{
return 1;
}

// otherwise
return 0;

}


@Override
public boolean equals(Object k) {
Person w = (Person) k;

if( getFname().equals(w.getFname()))
return true;
else
return false;
}






}


EMPLOYEE CLASS...........



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package person;

/**
*
* @author oayoa08
*/
public class Employee extends Person implements Comparable <Employee> {
private String status;


public Employee()
{
super();
this.status = "part-time";
}

//CONSTRUCTOR WITH PARAMETERS

public Employee(String newStatus)
{
super("David", "Green", 2007);
this.status = newStatus;
}

//MAKE NEW EMPLOYEE WITH SPECIFIED FNAME,LNAME,ENTYRYEAR AND STATUS
public Employee(String newFirst, String newLast, int newYear, String newStatus) {
super(newFirst, newLast, newYear);
this.status = newStatus;
}

public String getStatus()
{

return status;
}

public void setStatus( String sStatus )
{
this.status = sStatus;
}

// APPEND METHOD
@Override
public String makeEmail() {
StringBuffer email = new StringBuffer();
email.append(getFname());
email.append(".");
email.append(getLname());
email.append("@dkit.ie");
return email.toString();
}
//CONCAT METHOD
public String makeEmail2()
{
String email = getFname() + "." + getLname() + "@dkit.ie";
return email;
}

@Override
public boolean equals(Object newOne)
{
Employee p = (Employee) newOne;

if(status.equals(p.getStatus()))
{
return true;
}else
{
return false;
}
}

public int compareTo(Employee o) {
if(getYear() < o.getYear())
{
return -1;
}
if(getYear() > o.getYear())
{
return 1;
}
//otherwise
return 0;
}










}


ADMIN CLASS.........


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package person;

/**
*
* @author oayoa08
*/
public class Admin extends Employee implements Comparable<Employee>{

private int grade;


public Admin()
{
super();
this.grade = 1 ;
}

//CONSTRUCTOR WITH PARAMETERS

public Admin(int newAdmin)
{
super("David", "Green", 2007, "part-time");
this.grade = newAdmin;
}

//MAKE NEW EMPLOYEE WITH SPECIFIED FNAME,LNAME,ENTYRYEAR AND STATUS
public Admin(String newFirst, String newLast, int newYear, String newStatus, int newAdmin) {
super(newFirst, newLast, newYear, newStatus);
this.grade = newAdmin;
}

public int getGrade()
{
if((grade < 1)|| (grade > 7))
{
System.out.print("The value specified is outside the grade range");

}
return grade;
}

public void setGrade(int newAdmin)
{
this.grade = newAdmin;
}

// APPEND METHOD
@Override
public String makeEmail() {
StringBuffer email = new StringBuffer();
email.append(getFname());
email.append(".");
email.append(getLname());
email.append("@admin_mail.dkit.ie");
return email.toString();
}

//CONCAT METHOD
@Override
public String makeEmail2 ()
{
String email = getFname() + "." + getLname() + "@dkit.ie";
return email;
}


public int compareTo(Admin other) {

if (grade < other.getGrade())
{
return -1;
}

if (grade < other.getGrade())
{
return 1;
}

// otherwise
return 0;

}


public boolean equals(Object v) {
Faculty s = (Faculty) v;

if( getStatus().equals(s.getStatus()))
return true;
else
return false;
}
}



FACULTY CLASS........



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package person;

/**
*
* @author oayoa08
*/
public class Faculty extends Employee implements Comparable <Employee>
{

private String office;


public Faculty()
{
super();
this.office = " ";
}

//CONSTRUCTOR WITH PARAMETERS

public Faculty(String newoffice)
{
super("David", "Green", 2007, "part-time");
this.office = newoffice;
}

//MAKE NEW EMPLOYEE WITH SPECIFIED FNAME,LNAME,ENTYRYEAR AND STATUS
public Faculty(String newFirst, String newLast, int newYear, String newStatus, String newOffice) {
super(newFirst, newLast, newYear, newStatus);
this.office = newOffice;
}

public String getOffice()
{

return office;
}

public void setOffice( String oOffice )
{
this.office = oOffice;
}
// APPEND METHOD
@Override
public String makeEmail() {
StringBuffer email = new StringBuffer();
email.append(getFname());
email.append(".");
email.append(getLname());
email.append("@staff_mail.dkit.ie");
return email.toString();
}

//CONCAT METHOD
@Override
public String makeEmail2 ()
{
String email = getFname() + "." + getLname() + "@dkit.ie";
return email;
}

public int compareTo(Faculty other) {

if (getYear() < other.getYear())
{
return -1;
}

if (getYear() < other.getYear())
{
return 1;
}

// otherwise
return 0;

}


@Override
public boolean equals(Object v) {
Faculty s = (Faculty) v;

if( office.equals(s.getOffice()))
return true;
else
return false;
}



}
MAIN METHOD...............




/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package person;

import java.util.Arrays;




/**
*
* @author student
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {


Person[] staff = new Person[8];

staff[0] = new Student("Allen", "King", 2004, 5);
staff[1] = new Student("Joseph", "Keane", 2004, 4);
staff[2] = new Employee("joe", "King", 2002, "full-time");
staff[3] = new Employee("james", "King", 2005, "temporary");
staff[4] = new Faculty("kate", "jakie", 2009,"part-time", "E104");
staff[5] = new Faculty("Rita", "Rose", 2009,"full-time", "E107");
staff[6] = new Admin("abel", "King", 2000,"temporary", 5);
staff[7] = new Admin("cain", "fingles", 2001,"part-time", 5);


for(int i = 0; i < staff.length; i++)
{
System.out.print(staff[i].makeEmail()+ "\n");
// Java determines which makeEmail() method to use
//because the other classes overrides the makeEmail() from the abstract Person
// and the override methods allows java to use the
//override method specofied in eash class.
}













QUESTION???????.......

how do i Sort the staff array created in the MAIN, in order of last name, then by first name?
Was This Post Helpful? 0

#8 Guest_Guest*


Reputation:

Re: sorting array

Posted 01 March 2010 - 08:57 AM

nope sorri am a different ola....... dat ola asking about java is totally different from me.....
Was This Post Helpful? 0

#9 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10185
  • View blog
  • Posts: 37,603
  • Joined: 27-December 08

Re: sorting array

Posted 01 March 2010 - 08:59 AM

If you could also indent your code so that I can read it better and follow your logic flow. Also, please describe specifically the errors you are getting, possibly including the errors your compiler is giving you. Thanks for helping us help you! :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1