gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:06:09 25 4
gpt4 key购买 nike

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

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!");
}
}

最佳答案

尝试:

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!");
}
}

关于java - NullPointerException 用字符串长度初始化变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23253637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com