두 문자열의 연결이 회문 단어를 나타내는 경우 입력이 Strings로 구성된 회문 문제를 해결하려고합니다 (회문은 어느 방향 으로든 같은 방식으로 읽을 수있는 단어입니다. 예를 들어 다음 단어는 다음과 같습니다. 회문 : 시민, 레이더, 로터 및 마담) 그런 다음 배열에 저장하여 후자를 인쇄하고 그렇지 않으면 "0"을 인쇄하지만 null 인덱스를 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
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다