I have this snippet, and I want to know how I could traverse through the tokens of this file. As you can see, I read it with a Scanner, and I have infile as unresolved. It is understandable since infile is a Scanner, I mean, an object, but then how do I make that loop traverse the File? The idea is to read the contents of the file, which contains several words, convert each word to lowercase and put them all in a HashSet.
import java.io.File;
import java.util.*;
public class CheckSpelling{
public static void main(String[] args) {
//Create HashSet to store our data.
HashSet<String> words = new HashSet<String>();
try {
//Read file words.txt
Scanner filein = new Scanner (new File("/classes/s09/cs225/words.txt"));
}
catch(Exception e) {
e.printStackTrace();
}
//While there exists another word next...
while (filein.hasNext()) {
//Go to next word
String tk = filein.next();
//Convert that word into lower case...
tk.toLowerCase();
//add the word to our collection of data.
words.add(tk);
}
}
}
You put this in a java class and it will yield infile as unresolved. Please help me get over this. Let me know if you have an issue reproducing the Exception.
Thanks in advance.
>Solution :
Thats the solution:
You just had to correct the brackets.
public static void main(String[] args) {
//Create HashSet to store our data.
HashSet<String> words = new HashSet<String>();
try {
//Read file words.txt
Scanner filein = new Scanner (new File("your path"));
//While there exists another word next...
while (filein.hasNext()) {
//Go to next word
String tk = filein.next();
//Convert that word into lower case...
tk.toLowerCase();
//add the word to our collection of data.
words.add(tk);
}
}
catch(Exception e) {
e.printStackTrace();
}
}