Question

I am trying to create a method that strips a string of whitespace and punctuation to check if it is a palindrome. When filling a char array of stripped chars I get a null pointer exception. To me it makes perfect sense, i am filling the array of the same length with only letters or numbers. if there are leftover chars then i fill them with a space (later to be stripped with trim). Without char[] strippedInput = null; i get variable may not have been initialized. With it I get null pointer exception. I drew a simple diagram of what would happen to the stripped array when I input "if, then." and everything seemed to match up. There seemed to be a value for each array index of strippedInput yet netbeans is telling me that something is null.

    static boolean palindromeCheckC(String inputString)
    {
        boolean isPalin2 = false;

        char[] inChars = inputString.toCharArray();

        char[] strippedInput = null;

        int offsetIndex = 0; 

        for (int i = 0; i < inputString.length(); i++)
        {
            if ((Character.isLetter(inChars[i]) || Character.isDigit(inChars[i]
                )) == true)
            {
                strippedInput[i-offsetIndex] = inChars[i];
            }
            else offsetIndex++;
        }
        for (int i = inputString.length()- offsetIndex; i < inputString.length(); i++)
        {
            strippedInput[i] = ' ';
        }
        System.out.println(strippedInput);

        //to string
        //reverse
        //compare to    if 0 => isPalin2 = true


        return isPalin2;
     }
Was it helpful?

Solution

The problem is that instead of initializing your array, you set it to null. Try changing:

char[] strippedInput = null;

to

 char[] strippedInput = new char[inputString.length()];

I understand that the strippedInput will likely contain fewer characters than are in the inputString. However, as far as I know, it is possible that you will need the same amount of characters in the stripped array. If you do not need all of them, just write a null character at the end the data and it will work/print correctly. Regardless, this will solve your NullPointerException.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top