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();
          //read from file
        for (char c: ar)

        key = new char[10];
        while(ar[m]!=' ')
        dn[o]=new String(key);
      String[] cop = new String[20];
      for(int i=0;i<15; i++)
      for(int i=0;i<15;i++)
      for(int i=0;i<15; i++)

      //sort keys in alphabetical order
      for(int j=0; j<15;j++)
            for (int i=j+1 ; i<15; i++)
                        String temp= cop[j];
                        cop[j]= cop[i];
                        int tem=dr[j];

Recommended Answers

It woule be easier to use String's split method to split each line at the blanks into an array of words, then the last element in the array is the word you want.

Jump to Post

So ignore it and just take the last element, something like
String[] names = inputLine.split(" ");
String lastName = names[names.length -1]

Jump to Post

All 6 Replies

But if I use split() it would give me middle names too ,which i dont want.

So ignore it and just take the last element, something like
String[] names = inputLine.split(" ");
String lastName = names[names.length -1]

Yea..I will try out with this..Thanx.

String[] names = inputLine.split(" ");
String lastName = names[names.length -1]
gives only lastnames.I want firstnames also appended to the lastname.

This isn't a "we do your homework" service, you should be able to write that yourself. I was just pointing you in a good direction.
The first name is the first element in the array, so just create a String by appending the first element to the last element.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.