How to Import and Sort Alphabetically?

Asked By 10 points N/A Posted on -
qa-featured

I have to import a file of names and then be able to sort them alphabetically I've managed to import the file using the following code

  1. Import java.io.*;
  2. Public class Name{
  3. Public static void main(String[] args)throws IOException{
  4. String contents;
  5. File f = new File("names.txt");
  6. FileReader fr = new FileReader(f);
  7. BufferedReader br = new BufferedReader(fr);
  8. While (br.ready()){
  9. Contents = br.readLine();
  10. System.out.println(contents);
  11.  
  12. }
  13. fr.close();
  14. }
  15. }

Also I have managed to sort them alphabetically when manually entering the list of names as shown in the code below


  1. Public class DSA1
  2. {
  3. Public static void main(String[ ] args)
  4. {
  5. String[ ] names = {"James", "Anne", "Bill", "Maria", "Bob", "Jill", "Elvis", "Carol", "Dennis", "Mandy", "Steven", "Sian", "Harry", "Linda"};
  6. SortStringExchange (names);
  7. For ( int k = 0; k < 14; k++ )
  8. System.out.println( names [ k ] );
  9. }
  10.  
  11. Public static void sortStringExchange( String x [ ] )
  12. {
  13. Int i, j;
  14. String temp;
  15.  
  16. For ( i = 0; i < x.length – 1; i++ )
  17. {
  18. For ( j = i + 1; j < x.length; j++ )
  19. {
  20. If ( x [ i ].compareToIgnoreCase( x [ j ] ) > 0 )
  21. { // ascending sort
  22. Temp = x [ i ];
  23. x [ i ] = x [ j ]; // swapping
  24. x [ j ] = temp;
  25.  
  26. }
  27. }
  28. }
  29. }
  30. }

Anyone help me.

Thanks

 

SHARE
Best Answer by Hoting Gracia
Best Answer
Best Answer
Answered By 5 points N/A #118517

How to Import and Sort Alphabetically?

qa-featured

Hi Leonard,

JAVA is the language that is derived from the basics of C which is developed by Dennis Ritchie in the year 1972 and JAVA is just can be said as an advanced to C due to its ease of use and advantages.

Coming to JAVA we make use of the import statements to import files from the specific library we required by using import as the keyword.

As coming to your query the sorting and importing can be done automatically it cannot be as import statements automatically make use of the statements that are used by methods.

Sorting is done automatically in the way it can be sensed that by default the sorting is some in ascending order itself if we don't mention anything like asc or desc.

Hope you come to know that about the automatically import and sorting by default with ascending order with out any issues.

Thank You.

Related Questions