当我尝试编译此代码时,为什么 hasNext 行返回错误?
public static void main(String args[]) throws Exception
{
BufferedReader infile = new BufferedReader(new FileReader( "woodchuck.txt" ));
HashMap<String, Integer> histoMap = new HashMap<String,Integer>();
String word;
while((infile.hasNext()) !=null)
{
if(histoMap.get(word)==null)
histoMap.put(word,1);
else
histoMap.put(word, histoMap.get(word)+1);
}
infile.close();
System.out.print(histoMap);
}
最佳答案
BufferedReader
不提供方法hasNext()
。相反,一旦到达文件末尾,readLine()
就会简单地返回 null
。由于您没有阅读任何内容,因此您的代码包含无限循环。
关于java - 如何正确使用hasNext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29689313/