NullPointerException使用字符串长度初始化变量

时间:2014-04-23 19:35:21

标签: java recursion initialization

我们被告知要实现一种方法来检测字符串是否是具有迭代和递归的回文。我成功地用迭代实现了这个方法,但是当我尝试递归时我得到了这个错误。

Exception in thread "main" java.lang.NullPointerException
at recursion.RecursivePallindrome.isPallindrome(RecursivePallindrome.java:14)
at recursion.RecursivePallindrome.main(RecursivePallindrome.java:44)

我目前对出了什么问题一无所知。

package recursion;

public class RecursivePalindrome {

static String word;
public RecursivePalindrome(String a)
{
    a = word;
}

public static boolean isPalindrome()
{
    int start = 0;
    int end = word.length()-1; //Line 14
        char a = word.charAt(start);
        char z = word.charAt(end);
            Character.toLowerCase(a); Character.toLowerCase(z);

    if(start >= end)
    {
        if(Character.isLetter(a) && Character.isLetter(z))
        {
            if(a == z)
            {
                a++;
                z--;
            }
            else
                return false;
        }
        else if(!Character.isLetter(a))
            start++;
        else if(!Character.isLetter(z))
            end--;
        else
            return false;
    }

    return true;
}

public static void main(String[] args)
{
    new RecursivePalindrome("testing");
    if(isPalindrome())
        System.out.println("Is!");
    else
        System.out.println("Is not!");
}
}

3 个答案:

答案 0 :(得分:1)

尝试:

public RecursivePalindrome(String a) {
    word = a;
}

此代码有效,但不是递归!

package recursion;

public class RecursivePalindrome {

    static String word;

    public RecursivePalindrome(String a) {
        word = a;
    }

    public static boolean isPalindrome() {
        int start = 0;
        int end = word.length() - 1;
        char a = word.charAt(start);
        char z = word.charAt(end);
        Character.toLowerCase(a);
        Character.toLowerCase(z);

        while (start < end) {
            if (Character.isLetter(a) && Character.isLetter(z)) {
                if (a == z) {
                    start++;
                    end--;
                    a = word.charAt(start);
                    z = word.charAt(end);
                } else {
                    return false;
                }
            } else if (!Character.isLetter(a)) {
                start++;
            } else if (!Character.isLetter(z)) {
                end--;
            } else {
                return false;
            }
        }

        return true;
    }

    public static void main(String[] args) {
        new RecursivePalindrome("testing");
        if (isPalindrome())
            System.out.println("Is!");
        else
            System.out.println("Is not!");
    }
}

答案 1 :(得分:0)

这是我没有花时间的情况。在构造函数中,我将我的作业混淆了。

public RecursivePalindrome(String a)
{
a = word;
}

正确的代码是

public RecursivePalindrome(String a)
{
word = a;
}

答案 2 :(得分:0)

您忘记初始化word。 您可能想要更改

a = word;

word = a;