Results 1 to 4 of 4
  1. #1
    bMorgan is offline Member
    Join Date
    Nov 2010
    Posts
    9
    Rep Power
    0

    Default Help! Program cannot run. Error is "java.lang.NullPointerException".

    I want to output the frequency of the words in a sentence. The program can compile, but cannot run. The error is "java.lang.NullPointerException". Thank you very much.


    import java.util.Hashtable;
    import java.util.StringTokenizer;
    import java.util.Enumeration;

    public class Main{

    public void main(String[] args)
    {

    WordCount wc = new WordCount();
    wc.processLine("da do ro ro ro, da do ro ro");
    wc.print ();
    }
    }

    import java.util.Hashtable;
    import java.util.StringTokenizer;
    import java.util.Enumeration;


    public class WordCount
    {
    Hashtable ht;
    public WordCount ()
    {
    ht = new Hashtable ();
    }

    public void processLine (String s)
    {
    StringTokenizer st = new StringTokenizer (s, " ,.");
    while (st.hasMoreTokens()) {
    String word = st.nextToken();
    processWord (word.toLowerCase ());
    }
    }

    public void processWord (String word)
    {
    if (ht.containsKey (word)) {
    Integer i = (Integer) ht.get (word);
    Integer j = new Integer (i.intValue() + 1);
    ht.put(word, j);
    }
    else {
    ht.put(word, new Integer (1));
    }
    }

    public void print ()
    {
    Enumeration enum1 = ht.keys ();
    while (enum1.hasMoreElements ()) {
    String key = (String) enum1.nextElement ();
    Integer value = (Integer) ht.get (key);
    System.out.println ("{ " + key + ", " + value + " }");
    }
    }

    }

  2. #2
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    I don't see any NPE when I run it, although I have a hard time running it since the main method is not static. ;)
    Which line causes the problem?

  3. #3
    bMorgan is offline Member
    Join Date
    Nov 2010
    Posts
    9
    Rep Power
    0

    Default

    Thank you for replying. After i add " static ", it works. Thx.

  4. #4
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Quote Originally Posted by bMorgan View Post
    Thank you for replying. After i add " static ", it works. Thx.
    Were all problems so easy! :)

    You're welcome!

Similar Threads

  1. Replies: 3
    Last Post: 04-30-2010, 08:44 PM
  2. Replies: 4
    Last Post: 04-23-2010, 02:54 PM
  3. Replies: 1
    Last Post: 11-20-2009, 08:58 PM
  4. Replies: 5
    Last Post: 08-26-2009, 12:37 PM
  5. Replies: 4
    Last Post: 10-09-2008, 07:08 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •