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

3 個回答

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))
``````

`subStr == ending` 是比較這兩個`字串物件`是否相同
`subStr.equals(ending)` 則是比較這兩個字串的`值`是否相同