Hi all...
Trying to write a program for JavaRanch Cattle Drive
http://www.javaranch.com/drive/3/index.jsp#sort I have done half of the work. The following program take names from a text file and sort it based on first name. The question in JavaRanch Cattle Drive also asks for sorting the ArrayList for last name. Can anyone suggest how that can be achieved?
Here is the class file I've written so far that sorts first name.
--------------------------------------------------------------------
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import com.javaranch.common.*;
public class SortNames {
private
String fileName;
private String temp;
private boolean flag = true;
private TextFileIn file;
private ArrayList list;
public SortNames(String fileName)
{
super();
this.fileName = fileName;
execute();
}
public void execute()
{
try {
file = new TextFileIn(fileName);
}
catch (FileNotFoundException fnfe)
{
System.out.println(fnfe.getMessage());
}
list = new ArrayList();
try {
while(flag)
{
temp = file.readLine();
if(temp==null) {flag=false;break;}
else
list.add(temp);
}
Collections.sort(list);
for(int i =0; i<list.size();i++)
{
System.out.println(list.get(i));
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
new SortNames("c:/Practice/RA/Workspace/TutPrac/textnames.txt");
}
}
--------------------------------------------------------------
- Text file textnames.txt has following names
Adam Baum
Justin Case
Bill Joy
James Gosling
Walter Cronkite
Joe Montana
Abraham Lincoln
Connie Chung
Thank you all for help.
Raghav