0

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.

3
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by TTTHXC
0

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.

0

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.

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.