How to Import and Sort Alphabetically?
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
-
Import java.io.*;
- Public class Name{
- Public static void main(String[] args)throws IOException{
- String contents;
- File f = new File("names.txt");
- FileReader fr = new FileReader(f);
- BufferedReader br = new BufferedReader(fr);
- While (br.ready()){
- Contents = br.readLine();
- System.out.println(contents);
- Â
- }
- fr.close();
- }
- }
Also I have managed to sort them alphabetically when manually entering the list of names as shown in the code below
-
Public class DSA1
- {
- Public static void main(String[ ] args)
- {
- String[ ] names = {"James", "Anne", "Bill", "Maria", "Bob", "Jill", "Elvis", "Carol", "Dennis", "Mandy", "Steven", "Sian", "Harry", "Linda"};
- SortStringExchange (names);
- For ( int k = 0; k < 14; k++ )
- System.out.println( names [ k ] );
- }
- Â
- Public static void sortStringExchange( String x [ ] )
- {
- Int i, j;
- String temp;
- Â
- For ( i = 0; i < x.length – 1; i++ )
- {
- For ( j = i + 1; j < x.length; j++ )
- {
- If ( x [ i ].compareToIgnoreCase( x [ j ] ) > 0 )
- { // ascending sort
- Temp = x [ i ];
- x [ i ] = x [ j ]; // swapping
- x [ j ] = temp;
- Â
- }
- }
- }
- }
- }
Anyone help me.
Thanks
Â