i have a function that is supposed to check a string against a set of types, stored as a hash set in the class o.

however the function only works if there is one word. if the string conmtains more than 2 words, my program crashes with NullPointerException.

public static boolean checkOpcode(String opcode)
    {
        StringTokenizer st = new StringTokenizer(opcode);
        String[] basics = new String[st.countTokens()];
        for(int j = 0; j <= st.countTokens(); j++)
        {
            basics[j] = st.nextToken();
        }

        boolean[] ok = new boolean[basics.length];
        boolean correct = false;
        int t = 0;
        if (opcode.indexOf("0X") > 0)
            return true;
        else
        {
            for(int i = 0; i < ok.length;)
            {
                if(basics[i].contains("$")) /* <----- error occurs here, regardless of if there is a $ or not */
                {
                    ok[i] = true;
                    i++;
                }
                else if(o.ops.contains(basics[i]))
                    ok[i] = true;
                else ok[i] = false;
                i++;
            }

            for(boolean b : ok)
            {
                if(!b)
                    return false;
                else t+=1; 
            }
        }
        if(t == basics.length)
            correct = true;
        return correct;
    }

any ideas? i've tried String.split and that didn't work.

Looks like basics[i] is null for some value of i.
Print i and basics[i] at that point in the code to see which element is not initialised, them backtrack in your code with prints to see why/where the initialisation is missing.

In this code

        for(int j = 0; j <= st.countTokens(); j++)
        {
            basics[j] = st.nextToken();
        }

try this instead

        for(int i = 0, j = st.countTokens(); i < j; i++)
        {
            basics[i] = st.nextToken();
        }

also as James said, check if basics[i] is null when you are accessing it later on in your code.

rubberman, your code worked. the for loop was not detecting the number of tokens for some reason cuasing it to be null. thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.