Creating Lab6 and Person Classes

  1. Create two new classes: Lab6 and Person.
  2. Copy and paste the following code into Lab6.
    package lab6;
    
    public class Lab6 {
    	
    	// this is insertion sort
    	// precondition - all items in the array must be non-null Comparable objects
    	// postcondition - all items will be sorted in ascending order
        public static void insertionSort( Person [ ] personArray )
        {
            for( int i = 2; i < personArray.length; i++ )
            {
                Person tmp = personArray[ i ];
                int j = i;
    
                while(j > 0 && tmp.compare( personArray[ j - 1 ] ) < 0){
                    personArray[ j ] = personArray[ j - 1 ];
                    j--;
                }
                personArray[ j ] = tmp;
            }
        }
    	
    	
    	public static void main(String[] args){
    		System.out.println("Hello and Good Luck with your Debugging Exercise");
    		
    		// initialize an array of comparable objects
    		Person[] array = new Person[5];
    		array[0] = new Person("Edison", "Denise");
    		array[1] = new Person("Clarkson", "Happy");
    		array[2] = new Person("Edison","Thomas");
    		array[3] = null;
    		array[4] = new Person("Allen", "Woody");
    		
    		Lab6.insertionSort(array);
    		for(Person p: array){
    			System.out.println(p);
    		}
    	}
    }
    
  3. Copy and paste the following code into Person.
    package lab6;
    
    /**
     * The Person object is an object that maintains a Person's first
     * and last name.
     * 
     * @author Ryan
     *
     */
    public class Person {
    	private String lastName;
    	private static String firstName;
    	
    	public Person(String lastName, String firstName){
    		this.firstName = firstName;
    		this.lastName = lastName;
    	}
    	
    	/**
    	 * CompareTo will compare two Person objects based on their
    	 * last name and then first name in ascending order. 
    	 * @return 0 if first and last name are the same
    	 * -1 if this Person proceeds the other Person
    	 * 1 if this Person succeeds the other Person
    	 */
    	public int compare(Person other){
    		// get the result of comparing the last name
    		int result = this.lastName.compareTo(other.lastName);
    		switch(result){
    			case -1:
    			case 1:
    				return result;
    			default:
    				return this.firstName.compareTo(other.firstName);
    		}
    	}
    	
    	public String toString(){
    		return String.format("%s %s", firstName, lastName);
    	}
    	
    }