If someone could help me figure out how to search if a word exists in a file, I would greatly appreciate it. I do know how to read an entire text file though.
And this is what I have so far:
public static void main(String[] args) throws IOException {
File file = new File("words.txt");
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word you would like to search for:");
String word = sc.nextLine();
List<String> words = new ArrayList<>();
try {
sc = new Scanner(file).useDelimiter( ",");
while (sc.hasNext()) {
final String wordFromFile = sc.nextLine();
if (wordFromFile.contains(word)) {
// a match!
System.out.println("The entered word: " + word + " exists in the dictionary");
break;
}
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
}
}
Just iterate through all the words in file an insert each into a HashSet
from the file first. This is linear time O(n)
to accomplish, no way around this as you got to read in the whole file.
Assuming one word from file it's like:
HashSet<String> set = new HashSet<>();
while (sc.hasNext()) {
set.add(sc.nextLine();
}
If someone a sticker any they really want it read to a list type collection, you can generate a HashSet like this from the list:
Set<String> set = new HashSet<>(wordList);
Note: This conversion operation is also O(n)
, so to read it into a list and convert you're O(2n)
, which is still O(n)
, but if this list is long far from optimal
For the lookup and/or insertion of the new word you check, can then do it in O(1)
time.
if (set.contains(word)) {
//...blah..blah...bla...
} else {
set.add(word);
}
Hence the hash in the name HashSet
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments