and129
and129

Reputation: 31

How do I use hasNext properly?

Why does the hasNext line return an error when I try to compile this?

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);
}

Upvotes: 0

Views: 124

Answers (2)

candied_orange
candied_orange

Reputation: 7344

Switching to readLine() and adding an assignment to word are enough to get it outputting results:

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;
        } 
    }
}

Adding the try-with-resources will ensure infile will be closed even if an exception is thrown.

I added the working directory thing because it's so handy to know exactly where it's not finding the file. Useful when hard coding file names that aren't fully qualified paths.

Upvotes: 0

user4668606
user4668606

Reputation:

BufferedReader doesn't provide a method hasNext(). Instead readLine() simply returns null as soon as the end of the file is reached. And since you don't read anything, your code contains an endlessloop.

Upvotes: 4

Related Questions