Sorting question.

  • (2 Pages)
  • +
  • 1
  • 2

25 Replies - 1603 Views - Last Post: 29 September 2008 - 12:22 PM Rate Topic: -----

#1 emblem  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 16-April 08

Sorting question.

Posted 27 September 2008 - 06:50 AM

*not asking for code*

I'm trying to make a program where a user enters information: first name, last name, date of birth. Depending on what they choose in a menu, the program will display a sorted list of their first name or last name or by age.

I already have my code for the sorts already. That's not the hard part. I'm trying to plan how I'm going to display the code, and I'm not seeing how I would display the info.

Like I'll have the first name sorted and displayed, but it also needs to display the last name and the age, the info that wasn't sorted.
Right now the code I have has an array for first name, last name, date of birth.

So if I have these names
Matt AAA
Chris ZZZ
John DDD

It would show
Chris AAA
John ZZZ
Matt DDD

How would I keep the first name and the last name grouped together so when I sort the first name, it keeps track of the last name it belongs to.

So it will show like this
Chris ZZZ
John DDD
Matt AAA

Hope I explained it well.
I'm thinking I would need a 3 dimensional array(first name,last name, date of birth) but that seems to be highly complicated, especially to sort and search it.

How would I keep it 1 dimensional but have some way to keep the unsorted info of a person together with the sorted info of a person.

I'm not asking for code, just if what I"m asking is possible or if I will have to go into multi-dimensional array.

This post has been edited by emblem: 27 September 2008 - 06:54 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Sorting question.

#2 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2720
  • View blog
  • Posts: 11,448
  • Joined: 20-September 08

Re: Sorting question.

Posted 27 September 2008 - 08:13 AM

I would make your Person class with an appropriate toString method. Use custom Comparator to sort them
Was This Post Helpful? 0
  • +
  • -

#3 emblem  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 16-April 08

Re: Sorting question.

Posted 27 September 2008 - 11:05 AM

Someone just told me I should try and mirror all changes. When I discover that I need to swap two values in the firstNames[] array then just make that same change in the other two arrays.

So would something like this work
public class program2Sorts
{
//The [] _*string name* are so I can copy the results from the methods into these arrays and use them in other methods.
String [] _firstNames = new String [10];
String [] _lastNames = new String [10];
String [] _dateOfBirth = new String [10];
String [] _datePlaceHolder = new String[10];
public program2Sorts()
{

}



public void firstNameSort(String [] names String []dateOfBirth, int []compare, String [] placeholder)
{



int b = 0;
int c =0;
for (int i =1; i<names.length; i++)
{

// It sorts the names, but when it switches the elements in the index's it also
switches the dateOfBirth elements.

compare[b] =names[i].compareToIgnoreCase(names[i-1]);
if (compare[b]<0)
{
placeholder[c] = names[b];
datePlaceHolder[c] = dateOfBirth[b];

names[b]=names[b+1];
dateOfBirth[b] = dateofBirth[b+1]


names[b+1]=placeholder[c];
dateOfBirth[b+1] = datePlaceHolder[c];
b=0;
i=0;





}

else if (compare[b]>0)
{

b++;
}


}


for (int d = 0; d<names.length; d++)
{
_names[d]= names[d];
_dateOfBirth[d] = dateOfBirth[d];

System.out.println(_names[d] );
System.out.println (_dateOfBirth[d]);


}


}
}


Was This Post Helpful? 0
  • +
  • -

#4 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2720
  • View blog
  • Posts: 11,448
  • Joined: 20-September 08

Re: Sorting question.

Posted 27 September 2008 - 11:32 AM

You shouldn't be using arrays at all. All the data belong together in one class
Was This Post Helpful? 0
  • +
  • -

#5 emblem  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 16-April 08

Re: Sorting question.

Posted 27 September 2008 - 11:35 AM

What do you mean?

Why wouldn't I use an array?
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Sorting question.

Posted 27 September 2008 - 01:41 PM

View Postemblem, on 27 Sep, 2008 - 11:35 AM, said:

What do you mean?

Why wouldn't I use an array?

Use an array of Person instead of 3 arrays g00se means.

It will work with 3 arrays but when you do your switch you will need to change the 3 with 3 place holders: one for the first name, one for the last name and one for the age

If you had a Person object (wihich hold the 3 fields) you would change the 3 fields by switching a the 2 Person object.

class Person {
   String firstName;
   String lastName;
   int age;

   // constructor
   Person(String last, String first, int years) {
	 firstName = first;
	 lastName = last;
	 age = years;
   }
}

then you create an array of Person

Person[] person = new Person[10];

Manage to fill it

person[0] = new Person("AAAA", "John", 40);
person[1] = new Person("BBBB", "Mark", 50);
....

then in your loop

	// switch 2 persons
	if(person[b].name.compateToIgnoreCase(person[b+1].name)) {
		 Person temp = person[b];
		 person[b] = person[b+1];
		 person[b+1] = temp;
	}


Was This Post Helpful? 0
  • +
  • -

#7 emblem  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 16-April 08

Re: Sorting question.

Posted 27 September 2008 - 03:16 PM

Either I haven't written an object before or I don't know what one is.

Ok so all info about a person is in a Person object. When I'm doing the sort I switch the persons object..

// switch 2 persons
	if(person[b].name.compateToIgnoreCase(person[b+1].name)) {
		 Person temp = person[b];
		 person[b] = person[b+1];
		 person[b+1] = temp;



What is the person[b].name.compareToIgnoreCase(person[b+1].name))

part do? I'm not seeing what the .name part is for...

Also, is this Person object made in the same class as what I'm currently using?

Here is my totoal code
main program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.lang.String;
import javax.swing.JDialog;


public class Program2 
{
	
	public static void main (String [] args)
	{
	
		
		
		program2Sorts sorts = new program2Sorts();
		
			
			
			
		int numOfStudents;
		int choice=0;
	
		String inputString1;
		
		String inputString2;
		String name;
		String age = "";
		boolean flag;

	do 
	{
		flag = true;
	
		do
		{
			
			
		// Aks user how many names they will be entering.
		// Parses string to integer.
		// Checks if amount is higher than 10.
			inputString1 =JOptionPane.showInputDialog(null,"How many names will you be entering?", null );
			numOfStudents = Integer.parseInt(inputString1);
			
			if (numOfStudents >10)
			{
				JOptionPane.showMessageDialog(null,"Max amount of names is 10.","Warning",JOptionPane.WARNING_MESSAGE);
			}
			
		}while(numOfStudents>10);
			
			String [] names =new String [numOfStudents];
			String [] placeholder = new String [numOfStudents];
			String [] dates = new String [numOfStudents];
			String []datesFormated = new String[numOfStudents];	
			String [] _names;
			int [] compare= new int [numOfStudents];
			
			int n = 1;
		for (int a =0; a<names.length;a++)
			{
				
			
				name = JOptionPane.showInputDialog(null, "Enter the name of student "+ n,null);
				names[a] = name;
				
		
		
				/*age = JOptionPane.showInputDialog(null,"Enter the date of birth of " + names[a] + ":",null);
			
				dates[a] = age;
				
				datesFormated[a] = age.substring(4,8) + age.substring(0,2) + age.substring(2,4);
				
				*/
				
				n++;
				
			}
		
			
			choice = sorts.getChoice();
			if (choice == 1)
			{
					sorts.firstNameSort(names, compare, placeholder);
					choice = sorts.getChoice();
					System.out.println (flag);
			}
			
			else if (choice == 3)
			{
				
				sorts.oldestToYoungest(datesFormated, compare, placeholder);
				
			}
			else if (choice ==7)
			{
				flag = true;
			}
			
			else if (choice ==8)
			{
				flag = false;
			}
		
		
	
		
	}while(flag);
	
	System.out.println (flag);
		
		
		
	
			
		
		
	
		
		
	}
	
}


class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Scanner;
import javax.swing.table.*;

public class program2Sorts 
		String [] _names = new String [10];
	public program2Sorts()
	{
	
	}

	
	
	public void firstNameSort(String [] names, int []compare, String [] placeholder)
	{
		
			DefaultTableModel model = new DefaultTableModel();
		int b = 0;
		int c =0;
		for (int i =1; i<names.length; i++)
		{
		
	
			compare[b] =names[i].compareToIgnoreCase(names[i-1]);
			if (compare[b]<0)
			{
				placeholder[c] = names[b];
				names[b]=names[b+1];
			
				names[b+1]=placeholder[c];
				b=0;
				i=0;
				
				
				
			}
			
			else if (compare[b]>0)
			{
			 	
			b++;
			}
			
		
		}
		
	
		for (int d = 0; d<names.length; d++)
		{
				_names[d]= names[d];
		
			System.out.println(names[d] );
			
	
		}
		
		
	}
	
	public void youngestToOldest(String [] datesFormated, int []compare, String [] placeholder )
	{
		int b = 0;
		int c =0;
		for (int i =1; i<datesFormated.length; i++)
		{
		
	
			compare[b] =datesFormated[i].compareToIgnoreCase(datesFormated[i-1]);
			if (compare[b]<0)
			{
				placeholder[c] = datesFormated[b];
				datesFormated[b]=datesFormated[b+1];
			
				datesFormated[b+1]=placeholder[c];
				b=0;
				i=0;
				
				
				
			}
			
			else if (compare[b]>0)
			{
				
			b++;
			}
		}
		
		for (int d = 0; d<datesFormated.length; d++)
		{
		
		
			System.out.println (datesFormated[d] );
	
		}
		
		
		
	}
	
		public void oldestToYoungest(String [] datesFormated, int []compare, String [] placeholder )
	{
		int b = 0;
		int c =0;
		for (int i =1; i<datesFormated.length; i++)
		{
		
	
			compare[b] =datesFormated[i].compareToIgnoreCase(datesFormated[i-1]);
			if (compare[b]<0)
			{
				b++;
				
				
				
			}
			
			else if (compare[b]>0)
			{
				placeholder[c] = datesFormated[b];
				datesFormated[b]=datesFormated[b+1];
			
				datesFormated[b+1]=placeholder[c];
				b=0;
				i=0;
			
			}
		}
		
		for (int d = 0; d<datesFormated.length; d++)
		{
		
		
		System.out.println (datesFormated[d] );
	
		}
		
		
		
	}
	
	public int getChoice()
	{
		String inputString2;
		int choice;
		inputString2 = JOptionPane.showInputDialog(null,"1.Sort by first name.\n" + 
			"2.Sort by last name.\n3.Sort by age\n4.Search by first name\n"+
			"5.Search by last name\n6.Search by date of birth\n7.Input new names\n8.Quite program",null);
		choice = Integer.parseInt(inputString2);
		
		return choice;
	}
	
	public  void createTable()
	{
		
		
	}
	
	
}
	
/*	class Person 
	{
   String firstName;
   String lastName;
   int age;

   // constructor
   Person(String last, String first, int years) 
   	{
	 firstName = first;
	 lastName = last;
	 age = years;
   }


//then you create an array of Person

	Person[] person = new Person[10];

//Manage to fill it

person[0] = new Person("AAAA", "John", 40);
person[1] = new Person("BBBB", "Mark", 50);


//then in your loop

	// switch 2 persons
	if(person[b].name.compareeToIgnoreCase(person[b+1].name))
		 {
		 Person temp = person[b];
		 person[b] = person[b+1];
		 person[b+1] = temp;
   		 }
	
	}*/



And I'm trying to use the code you posted but I'm getting a lot of errors.

This post has been edited by emblem: 27 September 2008 - 04:10 PM

Was This Post Helpful? 0
  • +
  • -

#8 emblem  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 16-April 08

Re: Sorting question.

Posted 27 September 2008 - 07:12 PM

What would be the best way to understand an array of objects? I've been trying to google it and I'm not finding anything really constructive about it.
Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Sorting question.

Posted 27 September 2008 - 08:44 PM

View Postemblem, on 27 Sep, 2008 - 07:12 PM, said:

What would be the best way to understand an array of objects? I've been trying to google it and I'm not finding anything really constructive about it.

Java is an objects oriented language.
If you are planning to write Java code without using objects your are better to use C, Fortran or Cobol
Was This Post Helpful? 0
  • +
  • -

#10 emblem  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 16-April 08

Re: Sorting question.

Posted 27 September 2008 - 09:19 PM

I don't mind writing the object. I just need to find some more information on it. I just have never heard of making arrays out of objects.

I can't seem to find any good information about it online. If you know of any good sources I'd appreciate it.
Was This Post Helpful? 0
  • +
  • -

#11 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2720
  • View blog
  • Posts: 11,448
  • Joined: 20-September 08

Re: Sorting question.

Posted 28 September 2008 - 01:30 AM

http://www.javaworld...06-java101.html
Was This Post Helpful? 0
  • +
  • -

#12 emblem  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 16-April 08

Re: Sorting question.

Posted 28 September 2008 - 01:06 PM

I think I'm starting to understand it. I made the Person object and array and everything. I'm having a small problem though. I seem to be getting a null pointer exception when when I run the sorts.

At first I had the sorts in the same file as the main() code, the objectArrayTest. When all my code was there, it worked fine. I then moved it to a different class and into methods and it's giving me these null pointers.

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.lang.String;
import javax.swing.JDialog;

public class objectArrayTest
{	 
		
		public static void main (String [] args)
		{
			int choice;
			program2Sorts sorts = new program2Sorts();
			sorts.getInfo();
			System.out.println (sorts.numOfStudents);
			choice = sorts.getChoice();
			
			if (choice ==1)
			{
				sorts.firstNameSort();
				sorts.printResults();
			}
			else if (choice ==2)
			{
				sorts.lastNameSort();
			}
			else if (choice ==3)
			{
				sorts.youngestToOldestSort();
			}
			
			else
			{
				System.out.println("wrong");
			}
			
			
		
	
		
		
		
	

		
		
		
		
	
	
		
		
		
			
			
		
		}
		
}


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Scanner;


public class program2Sorts 
{
	
	int b=0;
	int numOfStudents;
	int choice=0;
	String inputString1;
	Person[] person;
	int [] compare;
	String firstName;
	String lastName;
	String dateOfBirth;
	String dateofBirthFormated;
	
	public program2Sorts()
	{
	
			
	}
	
	public void getInfo()
	{
		do
		{
			
			
		// Aks user how many names they will be entering.
		// Parses string to integer.
		// Checks if amount is higher than 10.
			inputString1 =JOptionPane.showInputDialog(null,"How many names will you be entering?", null );
			numOfStudents = Integer.parseInt(inputString1);
			
			
			if (numOfStudents >10)
			{
				JOptionPane.showMessageDialog(null,"Max amount of names is 10.","Warning",JOptionPane.WARNING_MESSAGE);
			}
			
		}while(numOfStudents>10);
			// create an array of Person(an object)
			
			Person[] person = new Person[numOfStudents];
			compare = new int[numOfStudents];
			
			
		 
			
				int n = 1;
			for (int index = 0; index<person.length; index++)
			{
				firstName = JOptionPane.showInputDialog(null, "Enter the first name of student "+ n,null);
			
			
				lastName = JOptionPane.showInputDialog(null, "What is " + firstName + " last name? ",null);
				
			dateOfBirth = JOptionPane.showInputDialog(null,"Enter the date of birth of " + firstName + ":",null);
		
			dateofBirthFormated = dateOfBirth.substring(4,8) + dateOfBirth.substring(0,2) + dateOfBirth.substring(2,4);
			
			person[index] = new Person(firstName, lastName, dateofBirthFormated);
			n++;
			}
	}
	
	public void firstNameSort()
	{
		b=0;
		for (int i =1; i<numOfStudents; i++)
		{
			compare[b]=person[i].firstName.compareToIgnoreCase(person[i-1].firstName);
		 if(compare[b]<0)
		 {
			 Person temp = person[b];
			 person[b] = person[b+1];
			 person[b+1] = temp;
			 b=0;
			i=0;
			 
		   }
		
			else if (compare[b]>0)
			{
				b++;
			}
		
		}
		
		
	}
	
	public void lastNameSort()
	{
		b=0;
		for (int i =1; i<numOfStudents; i++)
		{
			compare[b]=person[i].lastName.compareToIgnoreCase(person[i-1].lastName);
		 if(compare[b]<0)
		 {
			 Person temp = person[b];
			 person[b] = person[b+1];
			 person[b+1] = temp;
			 b=0;
			i=0;
			 
		   }
		
			else if (compare[b]>0)
			{
				b++;
			}
		
		}
		
		
	
	}
	
	public void youngestToOldestSort()
	{
		b=0;
		for (int i =1; i<numOfStudents; i++)
		{
		
	
			compare[b] =person[i].age.compareToIgnoreCase(person[i-1].age);
			if (compare[b]<0)
			{
				
			 
				b++;
				
				
			}
			
			else if (compare[b]>0)
			{
				Person temp = person[b];
			 	person[b] = person[b+1];
			 	person[b+1] = temp;
			 	b=0;
				i=0;
			
			}
		}
	
	}

	
	
	
	
		
		
		

	
	
	public int getChoice()
	{
		String inputString2;
		int choice;
		inputString2 = JOptionPane.showInputDialog(null,"1.Sort by first name.\n" + 
			"2.Sort by last name.\n3.Sort by age\n4.Search by first name\n"+
			"5.Search by last name\n6.Search by date of birth\n7.Input new names\n8.Quite program",null);
		choice = Integer.parseInt(inputString2);
		
		return choice;
	}
	
	public  void printResults()
	{
		/*for (int d = 0; d<numOfStudents; d++)
		{
			
		System.out.println (person[d].firstName);
	
		}*/
		
		System.out.println (person[0].firstName);
		
		
	}
	
	
}
	
	






		class Person
		{
		   String firstName;
		   String lastName;
		   String age;
		
		   // constructor
		   Person( String first, String last, String years) 
		   	{
			 firstName = first;
			 lastName = last;
			 age = years;
		   }
		   
	}



Not sure why it's giving me null pointer exceptions. I know the error has to do with some type of null value, but I don't see how there is one.
Was This Post Helpful? 0
  • +
  • -

#13 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Sorting question.

Posted 28 September 2008 - 01:42 PM

Ouf you have so many useless things

Here is a quick one... do what ever you want with it

First a class Person:
- into the constructor of it I put the calls to the 3 optionPane
- plus s static variale SortType so allow the 3 types of compare
- and its own compareTo method that react according to the SortType


import javax.swing.JOptionPane;


/** This class implements a person */
public class Person {
	
	// a common variable static for the type of sort
	static int SortType;
	
	// instance variables
	String lastName;
	String firstName;
	int age;
	
	// constructor that will prompt for the fields
	Person() {
		lastName = JOptionPane.showInputDialog(null, "Enter the last name of student", null);
		firstName = JOptionPane.showInputDialog(null, "Enter the first name of student", null);
        age = 0;
        while(age == 0) {
        	String str = JOptionPane.showInputDialog(null, "Enter the student age", null);
        	try {
        		age = Integer.parseInt(str);
        	}
        	catch(NumberFormatException e) {
        		
        	}
        }
	}
	
	// to display info
	public String toString() {
		return lastName + ", " + firstName + " age: " + age;
	}
	// to compare according to the SortType 2 persons
	int compareTo(Person p) {
		switch(SortType)
		{
		case 0:				// compare by lastName
			return lastName.compareToIgnoreCase(p.lastName);
		case 1:				// compare by firstName
			return firstName.compareToIgnoreCase(p.firstName);
		case 2:				// compare by age
			return age - p.age;
		}
		
		throw new IllegalStateException("SortType is invalid. Value: " + SortType);
	}

}



Now the Main class.
I did'nt bother calling optionPane for the number of students but you cann add that feature.

Plus a method sortPerson() that sort an array of Person


public class Main {

    public static void main(String args[]){

    	// ok 3 persons
    	Person[] p = new Person[3];
    	
    	// build them
    	for(int i = 0; i < p.length; i++)
    		p[i] = new Person();
    	
    	// the 3 type of sort
    	for(int i = 0; i < 3; i++) {
    		Person.SortType = i;
    		sortPerson(p);
    		System.out.println("Sort of type: " + i);
    		for(int j = 0; j < p.length; j++)
    			System.out.println(p[j]);
    		System.out.println();
    	}
    }
    
    private static void sortPerson(Person[] p) {
    	// don't iterate for nothing
    	boolean aSwitchOccurred = true;
    	while(aSwitchOccurred) {
    		aSwitchOccurred = false;
    		for(int i = 0; i < p.length - 1; i++) {
    			// if < 0 switch
    			if(p[i].compareTo(p[i+1]) > 0) {
    				Person tmp = p[i];
    				p[i] = p[i+1];
    				p[i+1] = tmp;
    				aSwitchOccurred = true;		// inform while() that we had a switch
    			}
    		}
    	}
    }
}



Hope this helps
Was This Post Helpful? 0
  • +
  • -

#14 emblem  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 16-April 08

Re: Sorting question.

Posted 28 September 2008 - 02:29 PM

Thanks.
I'm just looking through your code to make sure I understand everything. It's a much simpler version than mind it seems.

What was the issue with the null pointer error I was getting in that last code I posted?
Was This Post Helpful? 0
  • +
  • -

#15 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Sorting question.

Posted 28 September 2008 - 03:46 PM

View Postemblem, on 28 Sep, 2008 - 02:29 PM, said:

What was the issue with the null pointer error I was getting in that last code I posted?


Sorry, won't bother checking all your indices the [b+1], [b-1] and the rest
I think your learned a lot from all our replies... starting by making an array of Objects

Better to start all over with a clean design than trying to find out what was the flaw in the older one
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2