iT邦幫忙

0

【JAVA】輸出請益

/*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

1
海綿寶寶
iT邦大神 1 級 ‧ 2020-06-27 10:31:51
最佳解答

關鍵在於
== 是 compare if same object
.equal() 是 compare if same value

因此
以上面的程式來說
if (subStr == ending)會回傳 false
if (subStr.equals(ending))就會回傳 true

講得很清楚,謝謝

1
不明
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的內容是否相同

2
Darwin Watterson
iT邦研究生 1 級 ‧ 2020-06-27 10:41:23

試試看把

if (subStr == ending)

這行替換成

if (subStr.equals(ending))

https://ithelp.ithome.com.tw/upload/images/20200627/20109107aIJc4NNSGJ.jpg
解釋原因:
subStr == ending 是比較這兩個字串物件是否相同
subStr.equals(ending) 則是比較這兩個字串的是否相同
/images/emoticon/emoticon29.gif

我要發表回答

立即登入回答