英文:
Why is this giving me NullPointerException?
问题
我正在创建一个逐字回文("yes I can, can I yes?"),如下所示:
public class Palindrome {
LinkedQueue<String> queue;
LinkStack<String> stack;
public Palindrome() {
LinkedQueue<String> queue = new LinkedQueue<>();
LinkStack<String> stack = new LinkStack<>();
}
public boolean isPalindrome(String sentence) {
String[] sentenceSplit = sentence.split(" ");
for(String word : sentenceSplit) {
queue.enqueue(word.toLowerCase());
stack.push(word.toLowerCase());
}
while (stack.top() == queue.front()){
stack.pop();
queue.dequeue();
}
if(stack.size() == 0) {
return true;
}
return false;
}
public static void main(String[] args) {
Palindrome test = new Palindrome();
test.isPalindrome("can you you can");
}
}
在这里,代码中的问题是在for each
循环中,在将每个字符串入队和压栈时出现了nullpointerexception
异常。尽管在字符串数组中测试过字符串确实存在,但为什么会出现此错误呢?谢谢。
英文:
I am creating a word-by-word palindrome ("yes I can, can I yes?") as follows:
'''
public class Palindrome {
LinkedQueue<String> queue;
LinkStack<String> stack;
public Palindrome() {
LinkedQueue<String> queue = new LinkedQueue<>();
LinkStack<String> stack = new LinkStack<>();
}
public boolean isPalindrome(String sentence) {
String[] sentenceSplit = sentence.split(" ");
for(String word : sentenceSplit) {
queue.enqueue(word.toLowerCase());
stack.push(word.toLowerCase());
}
while (stack.top() == queue.front()){
stack.pop();
queue.dequeue();
}
if(stack.size() == 0) {
return true;
}
return false;
}
public static void main(String[] args) {
Palindrome test = new Palindrome();
test.isPalindrome("can you you can");
}
}
'''
In here, it says I receive a nullpointerexception during my for each loop where I enqueue and push each string in the string array, I have tested the strings in the string array and they do exist, so why am I receiving this error? Thanks.
答案1
得分: 1
Sure, here's the translated code:
queue = new LinkedQueue<String>();
stack = new LinkStack<String>();
英文:
Change
LinkedQueue<String> queue = new LinkedQueue<>();
LinkStack<String> stack = new LinkStack<>();
to
queue = new LinkedQueue<String>();
stack = new LinkStack<String>();
答案2
得分: 0
你的构造函数在声明变量,但你使用了未初始化的类属性。
将构造函数的内容移动到你的类属性中。
另外,在比较字符串时,你可能希望在 "while (stack.top() == queue.front())" 中使用 .equals 而不是 ==。
英文:
You constructor is declaring variables but you use your class attributes that are not initialized.
Move the content of your constructor into your class' attributes.
Also, you might want to use .equals instead of == when comparing Strings in
"while (stack.top() == queue.front())".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论