我遇到這個問題,我必須反轉(zhuǎn)出現(xiàn)的字符串的順序。我嘗試通過創(chuàng)建一個空字符串來反轉(zhuǎn)字符串,然后使用 for 循環(huán)添加后面的字符。但是,它實(shí)際上不適用于 null。下面是我嘗試過的代碼。 public static String reverse (String str){ String reverse= ""; for(int i=str.length()-1; i>=0; i--){ reverse+=str.charAt(i); } return reverse; }這是測試儀。 String s1=null; System.out.println (reverse(s1));//null System.out.println (reverse(""));// empty string System.out.println (reverse("a"));//a System.out.println (reverse("abc"));//cba System.out.println (reverse("atoyota"));// atoyota System.out.println (reverse("atOyotA"));//AtoyOta System.out.println (reverse("dad"));//dad System.out.println (reverse("Dad"));// daD System.out.println (reverse("DaD"));// DaD我執(zhí)行上面的代碼得到的錯誤是 Exception in thread "main" java.lang.NullPointerExceptionat PalindromeLab_BB.reverse(PalindromeLab_BB.java:62)at PalindromeLab_BB.main(PalindromeLab_BB.java:5)任何人都知道出了什么問題,或者如何解決它?任何幫助將不勝感激 :)。
1 回答

慕田峪7331174
TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個贊
null只需在開頭添加一個檢查并設(shè)置str為 a Stringof null:
public static String reverse (String str){
//New code
if (str == null) {
str = "null";
}
String reverse = "";
for(int i = str.length() - 1; i >= 0; i--){
reverse += str.charAt(i);
}
return reverse;
}
空時輸出:
圖片
當(dāng)然,您也可以對案例進(jìn)行硬編碼return "llun";,這樣它實(shí)際上不會進(jìn)入循環(huán),或者return null;如果您想返回null自身而不是反轉(zhuǎn)它:
if (str == null) {
return "llun";
//return null; //If you want to just return null instead
}
添加回答
舉報(bào)
0/150
提交
取消