【发布时间】:2022-07-20 22:14:37
【问题描述】:
我有这个 sn-p,我想知道如何遍历这个文件的标记。如您所见,我使用扫描仪阅读它,并且我的 infile 未解决。这是可以理解的,因为 infile 是一个扫描器,我的意思是,一个对象,但是我如何使该循环遍历文件?这个想法是读取文件的内容,其中包含几个单词,将每个单词转换为小写并将它们全部放在一个 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);
}
}
}
你把它放在一个java类中,它会产生未解析的infile。请帮我克服这个问题。如果您在重现异常时遇到问题,请告诉我。
提前致谢。
【问题讨论】:
-
您的 filein 变量在您的 try-catch 块的花括号中定义。它不存在于外部。在 try-catch 中移动你的 while 循环。
标签: java loops dictionary processing code-snippets