通过散列集迭代的问题
我的问题是当我运行我的主方法时,没有打印任何东西。 我对HashSet
很新,我担心它不起作用,因为有些东西真的很愚蠢。 dic
最初是ArrayList
,我只是试图将其转换为HashSet
以提高效率。通过散列集迭代的问题
private Set<String>dic = new HashSet<String>(100000);
public void dictionary(){//reads/intializes arraylist dic from a file
File data = new File("dictionaryForJava.txt");
Scanner scanner=null;
try {
scanner = new Scanner(data);
while (scanner.hasNextLine()) {
dic.add(scanner.nextLine());
}
} catch (FileNotFoundException fnfe) {}
if(scanner!=null)scanner.close(); // need if if file missing
}
public void print() throws IOException{
Iterator it = dic.iterator();
while(it.hasNext())
{
String value =(String)it.next();
System.out.println(value);
}
}
public static void main (String[] args)throws IOException{
words test = new words();
test.dictionary();
test.print();
}
很有可能没有找到文件dictionaryForJava.txt
。你不能吃的异常没有至少打印一些调试信息,试试这个:
catch (FileNotFoundException fnfe) {fnfe.printStackTrace();}
上面会显示在控制台中,如果有一些问题读取文件。
问题不在于读取文件,因为当所有内容都是arrayList – 2013-03-14 21:36:14
@LouisB时,它完美地工作,不要吃异常,处理它并对它做些什么。留下一个空的“catch”块是非常糟糕的做法。 – 2013-03-14 21:42:54
将此加载到Eclipse或您最喜欢的IDE中,在dictionary()的开头设置一个断点并遍历代码 – 2013-03-14 21:49:44
它在dictionary()方法中添加了什么?你需要在catch块中打印异常。看起来无论你有FileNotFoundException(或)什么都不读。 – kosa 2013-03-14 21:34:00
不要隐藏异常(就像你使用'FileNotFoundException'一样)。至少,请将错误记录到控制台。 – SJuan76 2013-03-14 21:34:31
我刚刚运行它,对我来说它正在工作。当然只有当指定的文件存在并且包含适当的内容时。我同意其他意见。你不应该忽略FileNotFoundException。 – Thomas 2013-03-14 21:44:40