Write Java code for methods public Dictionary( File f ) throws IllegalArgumentEx
ID: 3810140 • Letter: W
Question
Write Java code for methods
public Dictionary( File f ) throws IllegalArgumentException
A one parameter constructor that takes a File object as a parameter. The dictionary should be populated with the words
stored in the file. If anything goes wrong (the file does not exist, it is not readable) the constructor should throw an instance
of IllegalArgumentException with an appropriate message. (File is in txt.)
Other methods in this class:
public boolean isWord( String str )
A method that determines if the argument string str is one of the words stored in this dictionary. This method should use binary
search.
public boolean isPrefix( String str )
A method that determines if the argument string str is a prefix for at least one of the words stored in this dictionary. This method
should use binary search like approach.
You may need additional private methods that provide the actual recursive implementation of algorithms that search for words and prefixes.
Explanation / Answer
public class Dictionary1 {
File dictFile;
ArrayList<String> list;
public Dictionary1(File dictFile) {
this.dictFile = dictFile;
load();
}
private void load() throws IllegalArgumentException {
int lines = 0;
String word;
try(BufferedReader br = new BufferedReader(new FileReader(dictFile))) {
while (br.readLine()!=null)
lines++;
} catch (FileNotFoundException ex) {
throw new IllegalArgumentException();
} catch (IOException ex) {
throw new IllegalArgumentException();
}
list = new ArrayList<>(lines);
try(BufferedReader br = new BufferedReader(new FileReader(dictFile))) {
while ((word = br.readLine())!=null){
list.add(word);
}
} catch (FileNotFoundException ex) {
throw new IllegalArgumentException();
} catch (IOException ex) {
throw new IllegalArgumentException();
}
Collections.sort(list);
}
public boolean isWord( String str ) {
int min = 0;
int max = list.size();
while (min <= max){
int mid = (min+max)/2;
if (list.get(mid).equals(str))
return true;
else if (list.get(mid).compareTo(str) < 0)
min = mid + 1;
else
max = mid - 1;
}
return false;
}
public boolean isPrefix( String str ){
int min = 0;
int max = list.size();
while (min <= max){
int mid = (min+max)/2;
if (list.get(mid).startsWith(str))
return true;
else if (list.get(mid).compareTo(str) < 0)
min = mid + 1;
else
max = mid - 1;
}
return false;
}
}
NOTE:
the dictionary contatins one word per line.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.