gpt4 book ai didi

java - Java中如何用特定数字填充空数组?

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

我正在尝试解决输入由 Strings 组成的回文问题,如果两个字符串的串联表示一个回文单词(回文是一个可以在任一方向以相同方式读取的单词。例如,下列的单词是回文:civic、radar、rotor 和 madam)然后将其保存到数组中以稍后打印它,否则打​​印“0”但我在用零填充空索引时遇到问题,这里我得到异常

 for (int re = 0; re < result.length; re++) {
if (result[re].equals(null)) {
result[re] = "0";
}
}
"Exception in thread "main" java.lang.NullPointerException"

这是我的完整代码

import java.util.Scanner;

public class Palindrome {

public static String reverse(String R2) {
String Reverse = "";
String word_two = R2;

int ln = word_two.length();
for (int i = ln - 1; i >= 0; i--) {
Reverse = Reverse + word_two.charAt(i);
}
return Reverse;
}

public static void main(String[] args) {
Scanner inpoot = new Scanner(System.in);


int stop = 0;
String pal1;
int Case = inpoot.nextInt();
String result[] = new String[Case];
String Final;
int NumberofWords;
for (int i = 0; i < Case; i++) {
NumberofWords = inpoot.nextInt();

String words[] = new String[NumberofWords];
for (int array = 0; array < words.length; array++) {
words[array] = inpoot.next();
}

for (int word1 = 0; word1 < NumberofWords; word1++) {
if (stop > Case) {
break;
}
for (int word2 = 0; word2 < NumberofWords; word2++) {
if (word1 == word2) {
continue;
}

Final = "" + words[word1].charAt(0);
if (words[word2].endsWith(Final)) {
pal1 = words[word1].concat(words[word2]);
} else {
continue;
}
if (pal1.equals(reverse(pal1))) {

result[i] = pal1;
stop++;
break;
} else {
pal1 = "";
}

}

}


}
// HERE IS THE PROBLEM
for (int re = 0; re < result.length; re++) {
if (result[re].equals(null)) {
result[re] = "0";
}
}
for (int x = 0; x < result.length; x++) {
System.out.println("" + result[x]);
}

}

}

最佳答案

诸如 anObject.equals(null) 这样的测试没有任何意义。事实上,如果 anObject 为 null,它将抛出 NullPointerException (NPE),如果不是,它将始终返回 false。

要测试引用是否为 null,只需使用 anObject == null

关于java - Java中如何用特定数字填充空数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26437764/

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