hi.
The file called test.txt contains names as
John Smith
Walter H. Kepler
Gary Davies and so on..
I need to read only the lastnames from the file so that I can sort it in alphabetical order.For this I read the name as John Smith then go backwards as h,t,i,m,S till space is encountered in the name so that I can get only lastname.Please help me out with this as am stuck over here.The following is the code I tried but gives Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at javaapplication30.Sort.main(Sort.java:55).
Please suggest where the code needs to be rectified.Any help will be apreciated.thank you.
public static String[] dn = new String[20];
public static int[] dr = new int[20];
public static void main(String[] args) throws FileNotFoundException, IOException{
String filename = "C:\\test.txt";
Scanner inp = new Scanner ( new java.io.File(filename) );
System.out.println("Data read from file " + filename);
BufferedReader in = new BufferedReader(new FileReader(filename));
String s;
int m =0, o=0;
char[] ar = new char[100];
char[] key = new char[10]
s= in.readLine();
o=0;
//read from file
while(s!=null){
ar=s.toCharArray();
for (char c: ar)
System.out.println(ar);
m=0;
key = new char[10];
while(ar[m]!=' ')
{
//System.out.println(ar[m]);
key[m]=ar[m];
m++;
}
//System.out.println(key);
dn[o]=new String(key);
o++;
s=in.readLine();
}
in.close();
String[] cop = new String[20];
for(int i=0;i<15; i++)
cop[i]=dn[i];
for(int i=0;i<15;i++)
dr[i]=i;
for(int i=0;i<15; i++)
System.out.print(cop[i]);
System.out.println();
//sort keys in alphabetical order
for(int j=0; j<15;j++)
{
for (int i=j+1 ; i<15; i++)
{
if(cop[i].compareTo(cop[j])<0)
{
String temp= cop[j];
cop[j]= cop[i];
cop[i]=temp;
int tem=dr[j];
dr[j]=dr[i];
dr[i]=tem;
}
}