如何正确使用hasNext?

时间:2015-04-17 02:39:46

标签: java

当我尝试编译时,为什么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);
}

2 个答案:

答案 0 :(得分:4)

BufferedReader未提供方法hasNext()。相反,只要文件结束,readLine()就会返回null。由于你没有阅读任何内容,你的代码包含了一个无限循环。

答案 1 :(得分:0)

切换到readLine()并将作业添加到word足以让它输出结果:

import java.io.*;
import java.util.HashMap;

public class ReadFile {
    public static void main(String args[]) throws Exception
    {
        try(BufferedReader infile = new BufferedReader(new FileReader("woodchuck.txt"))) 
        {
            HashMap<String, Integer> histoMap = new HashMap<String,Integer>();

            String word;
            while((word = infile.readLine()) != null)
            {
                if(histoMap.get(word) == null)
                    histoMap.put(word,1);
                else
                    histoMap.put(word, histoMap.get(word)+1);
            }
            System.out.print(histoMap);
        } 
        catch (FileNotFoundException e) 
        {
            String pwd = System.getProperty("user.dir") + "\\";
            FileNotFoundException e2 = new FileNotFoundException(pwd + e.getMessage());
            e2.initCause(e);
            throw e2;
        } 
    }
}

添加try-with-resources即使发生异常也会确保infile关闭。

我添加了工作目录,因为它非常方便地知道它找不到文件的确切位置。在硬编码非完全限定路径的文件名时很有用。

相关问题