Need help to create main method for code below public static String [] readDicti
ID: 3657980 • Letter: N
Question
Need help to create main method for code below
public staticString[] readDictionary()
{
Scannerfilein=newScanner(newFile("dictionary.txt"));
// exactly 9992 lines in the file
String[] output=newString[9992];
for(inti=0; i<output.length; i++)
output[i]=filein.nextLine().trim();
filein.close();
returnoutput;
}
public static void selectionSort(String[] array)
{
for(int i = 0; i < array.length-1; i++)
{
// select lowest element
int min_idx = i;
for(int j = i+1; j < array.length; j++)
// case insensitive
if(array[j].toLowerCase().compareTo(array[min_idx].toLowerCase()) < 0)
min_idx = j;
// swap
String temp = array[min_idx];
array[min_idx] = array[i];
array[i] = temp;
}
}
public static int linearSearch(String[] array, String s)
{
for(int i = 0; i < array.length; i++)
// case insensitive
if(array[i].equalsIgnoreCase(s))
return i;
return -1;
}
Explanation / Answer
public static void main(String[] args) throws IOException
{
// read dictionary
String[] dictionary = readDictionary();
System.out.println("Array loaded. First five entries: ");
// display first 5 and last 5 elements
for(int i = 0; i < 5; i++)
System.out.println(dictionary[i]);
System.out.println(" Last five entries: ");
for(int i = dictionary.length-5; i < dictionary.length; i++)
System.out.println(dictionary[i]);
System.out.println(" Sorting array ");
// sort dictionary
selectionSort(dictionary);
System.out.println("Array sorted. First five entries: ");
// display first 5 and last 5 elements
for(int i = 0; i < 5; i++)
System.out.println(dictionary[i]);
System.out.println(" Last five entries: ");
for(int i = dictionary.length-5; i < dictionary.length; i++)
System.out.println(dictionary[i]);
// allow user to search
Scanner kb = new Scanner(System.in);
while(kb.hasNextLine())
{
// stop if no word entered
if(!kb.hasNext())
break;
System.out.print("Enter a String to search for in the array: ");
String word = kb.next();
int idx = linearSearch(dictionary, word);
if(idx >= 0)
System.out.println("Your string was found at position "+idx);
else
System.out.println("Your string was not found.");
}
System.out.println(" Program complete.");
}