2014-10-18 92 views
0

我试图解决一个回文问题,输入由字符串组成,如果两个字符串的连接表示一个回文字(回文是一个字,它可以在任一方向上以相同的方式读取,例如,以下 文字是palindromes:公民,雷达,转子,和夫人) 然后将其保存到数组打印它后面,否则打印“0” 但我有问题填充空索引零,这里我得到异常如何用Java中的特定数字填充空数组?

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]); 
     } 

    } 

} 

回答

1

诸如anObject.equals(null)之类的测试没有意义。事实上,如果anObject为空,它将抛出一个NullPointerException(NPE),如果不是,它将始终返回false。

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

0

如果要检查result[re]是否为null,则不能使用equals。使用身份比较:

if (result[re] == null) { 
    result[re] = "0"; 
}