-2

I was making a program where it would count how many times every word was used in a random paragraph. It compiles, but when i try to run it its giving me a NullPointerException.

Here's the code:

import java.util.StringTokenizer; 

class Count
{
    int count;
    String name;

    void SetCount(int c, String n)
    {
        count = c;
        name = n;
    }

    void Show()
    {
        System.out.print("Name=" + name);
        System.out.print("Count=" + count);
    }
}

class Contains2 extends Count
{
    public static void main(String args[])
    {
        String s = "Once you have made it to the box office and gotten your tickets, you are confronted with the problems of the theater itself. If you are in one of the run-down older theaters, you must adjust to the musty smell of seldom-cleaned carpets. Escaped springs lurk in the faded plush or cracked leather seats, and half the seats you sit in seem loose or tilted so that you sit at a strange angle. The newer twin and quad theaters offer their own problems. Sitting in an area only one-quarter the size of a regular theater, moviegoers often have to put up with the sound of the movie next door. This is especially jarring when the other movie involves racing cars or a karate war and you are trying to enjoy a quiet love story. And whether the theater is old or new, it will have floors that seem to be coated with rubber cement. By the end of a movie, shoes almost have to be pried off the floor because they have become sealed to a deadly compound of spilled soda, hardening bubble gum, and crushed Ju-Jubes";
        int size, i, count = 0, j;

        size = s.length();
        String[] test = new String[size];

        Count[] c = new Count[size];

        StringTokenizer st = new StringTokenizer(s, " ");   

        while (st.hasMoreTokens())
        {
            for (i=0; i < size; i++)
            {
                test[i] = st.nextToken();
                c[i].SetCount(1, test[i]);
            }
        }

        for (i=0; i<size; i++)
        {
            for (j=0; j<size; j++)
            {
                if (c[i].name.equals(test[j]))
                    c[i].count+=1;
            }
        }

        for (i=0; i<size; i++)
        {
            c[i].Show();
        }
    }   
}
Will
  • 24,082
  • 14
  • 97
  • 108
Mohit Saxena
  • 89
  • 1
  • 12
  • Not a duplicate as the specific problem with `StringTokenizer` isn't addressed there. This is a control flow issue. – Will Jul 11 '16 at 09:37
  • Btw Mohit, your problem is this line `c[i].SetCount(1, test[i])`, because your `c` array contains `null` elements, not `Count` instances. Fix that. Also, please accept the suggested duplicate, since it matches your question here. – Tom Jul 11 '16 at 09:44
  • yeah i forgot to initialize those instances...my bad :O it seems to be running now but i am getting a weird output of:- Name=outCount=143 – Mohit Saxena Jul 11 '16 at 10:14

2 Answers2

1

The main problem is, even though you've created an array of Count[], you haven't actually initialized a Count() object at each position in the array.

Count[] c = new Count[size];

This initializes the array itself, but it still does not place an initialized Count() object at each position of the array. You need to actually create and assign these new objects with new Count() like this:

for (int i=0; i<size; i++)
{
    c[i] = new Count();
}

Another problem seems to be here:

while (st.hasMoreTokens())
{
    for (i=0; i<size; i++)
    {
        test[i] = st.nextToken();
        c[i].SetCount(1, test[i]);
    }
}

You loop while st.hasMoreTokens(), but then you keep calling st.nextToken() size times, and the end is reached.

Try this instead:

import java.util.StringTokenizer;


class Contains2 extends Count
{
    public static void main(String args[])
    {
        String s = "Once you have made it to the box office and gotten your tickets, you are confronted with the problems of the theater itself. If you are in one of the run-down older theaters, you must adjust to the musty smell of seldom-cleaned carpets. Escaped springs lurk in the faded plush or cracked leather seats, and half the seats you sit in seem loose or tilted so that you sit at a strange angle. The newer twin and quad theaters offer their own problems. Sitting in an area only one-quarter the size of a regular theater, moviegoers often have to put up with the sound of the movie next door. This is especially jarring when the other movie involves racing cars or a karate war and you are trying to enjoy a quiet love story. And whether the theater is old or new, it will have floors that seem to be coated with rubber cement. By the end of a movie, shoes almost have to be pried off the floor because they have become sealed to a deadly compound of spilled soda, hardening bubble gum, and crushed Ju-Jubes";
        int size, count = 0;


        StringTokenizer st = new StringTokenizer(s, " ");
        size = st.countTokens();

        Count[] c = new Count[size];
        String[] test = new String[size];

        while (st.hasMoreTokens())
        {
            String token = st.nextToken();

            for (int i=0; i<size; i++)
            {
                test[i] = token;

                c[i] = new Count();
                c[i].SetCount(1, token);
            }
        }

        for (int i=0; i<size; i++)
        {
            for (int j=0; j<size; j++)
            {
                if (c[i].name.equals(test[j]))
                    c[i].count+=1;
            }
        }

        for (int i=0; i<size; i++)
        {
            c[i].Show();
        }
    }
}

public class Count
{
    protected int count;
    protected String name;

    public void SetCount(int c, String n)
    {
        count = c;
        name = n;
    }

    public void Show()
    {
        System.out.println("Name=" + name);
        System.out.println("Count=" + count);
    }
}
Will
  • 24,082
  • 14
  • 97
  • 108
  • still same Exception – Mohit Saxena Jul 11 '16 at 09:39
  • 2
    `NoSuchElementException` (thrown by `nextToken`) != `NullPointerException` (reported by OP) .... or written as a question: how should that snippet from OPs code throw a `NullPointerException` and how does your code fix that? – Tom Jul 11 '16 at 09:39
  • The whole loop doesn't make much sense. `test[i]` will also not be set. – Fildor Jul 11 '16 at 10:06
  • Fixed now, sorry! There's no more `NullPointerException`, but there may be other problems with the code for you to debug. – Will Jul 11 '16 at 10:09
  • yeah..but the output i am getting is Name=outCount=143Name=outCount=143Name=outCount=143Name=outCount=143Name=outCount=143Name=outCount=143Name=outCount=143........ – Mohit Saxena Jul 11 '16 at 10:31
  • Did you change `Count` as above, too? It should at least be on separate lines. But this is now a logic problem in the code... Probably because you're comparing each word with itself and incrementing the count. – Will Jul 11 '16 at 10:33
  • Why downvote? I spent about 30 minutes of time working on this.The NullPointerException is fixed. The right thing to do would be to accept this answer, and post a new one about the logic issues, showing your expected output. – Will Jul 11 '16 at 10:33
  • i did not downvote. i clicked the "tick mark" to accept it – Mohit Saxena Jul 11 '16 at 10:39
  • Sorry to assume, maybe someone else downvoted :) Thanks! – Will Jul 11 '16 at 10:40
  • now the problem is that it will also include the very own word while comparing which will set the count to an extra +1. any way to skip the element i am running the loop for? i am noob :( – Mohit Saxena Jul 11 '16 at 10:52
  • @MohitSaxena *"now the problem"* New issue? Then create a new question. – Tom Jul 11 '16 at 11:27
1

When you do c[i].SetCount(.....) the object at c[i] has not been initialised with new Count()

jr593
  • 287
  • 1
  • 8