/*Complete the solution so that it returns true if the first
argument(string) passed in ends with the 2nd argument (also a string).
*/
public class Kata {
public static boolean solution(String str, String ending) {
int sub = str.length() - ending.length();
String subStr = str.substring(sub);
System.out.println(subStr + " " + ending);
if (subStr == ending) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
System.out.println(solution("samurai", "ai"));
}
}
Output
ai ai
false
請教為什麼會輸出false
關鍵在於==
是 compare if same object
.equal()
是 compare if same value
因此
以上面的程式來說if (subStr == ending)
會回傳 falseif (subStr.equals(ending))
就會回傳 true
public class Test01 {
public static boolean solution(String str, String ending) {
int sub = str.length() - ending.length();
String subStr = str.substring(sub);
System.out.println(subStr + " " + ending);
if (subStr.equals(ending)) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
System.out.println(solution("samurai", "ai"));
}
}
1.str1==str2 :判斷str1與str2是否同一個物件
2.str1.equals(str2):判斷str1與str2的內容是否相同
試試看把
if (subStr == ending)
這行替換成
if (subStr.equals(ending))
解釋原因:subStr == ending
是比較這兩個字串物件
是否相同
subStr.equals(ending)
則是比較這兩個字串的值
是否相同