Reputation: 47
I need to read in a text file and then sort each strings alphabetically into array (don't need to worry about case sensitivity).
I need to use the arrays to to do binary search later.
Here is the code:
public class project2 {
public static void main( String[] args ) throws IOException {
String[] list = { "" };
list = load_list( "wordlist.txt" );
ArrayList<String> words =new ArrayList<String>(Arrays.asList(list));
File fileReader = new File( "wordlist.txt" );
Scanner inputFile = new Scanner( fileReader );
Collections.sort(words,String.CASE_INSENSITIVE_ORDER);
}
public static String[] load_list( String wordlist ) throws IOException {
File fileReader = new File( "wordlist.txt" );
Scanner inputFile = new Scanner( fileReader );
List<String> L = new ArrayList<String>();
while ( inputFile.hasNextLine() ) {
L.add(inputFile.nextLine());
}
return L.toArray(new String[L.size()]);
}
}
The first block of code is my attempt to read and sort them
the 2nd block is to read each line of strings
Im ahead of myself but can someone give me hint on using the result of these codes to do sequential/binary search?
Upvotes: 0
Views: 2686
Reputation: 26094
include following imports.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
and
change
ArrayList<String> words = Arrays.asList(list);
to
ArrayList<String> words =new ArrayList<String>(Arrays.asList(list));
if you want to ignore case use like below.
Collections.sort(words,String.CASE_INSENSITIVE_ORDER);
update
change your load_list() method like this.
public static String[] load_list( String filename ) throws IOException {
File fileReader = new File( filename );
Scanner inputFile = new Scanner( fileReader );
List<String> L = new ArrayList<String>();
while ( inputFile.hasNextLine() ) {
L.add(inputFile.nextLine());
}
return L.toArray(new String[L.size()]);
}
change your main() method like this.
public static void main(String[] args) throws IOException {
String[] list = { "" };
list = load_list( "wordlist.txt" );
ArrayList<String> words = new ArrayList<String>(Arrays.asList(list));
Collections.sort(words,String.CASE_INSENSITIVE_ORDER);
}
and include following imports
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
to print the ArrayList use like below
for(String s: list){
System.out.println(s);
}
Upvotes: 1