Adz*_*Adz 0 java eclipse string return
为Java做一些初学者问题:
给定两个字符串,将它们附加在一起(称为"连接")并返回结果.
但是,如果连接创建了一个双字符,则省略其中一个字符,因此"abc"和"cat"会产生"abcat".
我的代码:
public static String conCat(String a, String b) {
//abc (c) == cat (c)
if (a.substring(a.length()-1,a.length()) == b.substring(0,1)) {
//return (ab) + (cat)
return a.substring(0,a.length()-2) + b;
//cat (c) == abc (c)
} else if(b.substring(0,1) == a.substring(a.length()-1,a.length())) {
//return (abc) + (at)
return a + b.substring(2,b.length());
} else if (a.equals("") || b.equals("")) {
return a + b;
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么Eclipse无法识别String返回.
首先,您将字符串与==进行比较,并通过引用对它们进行比较.这意味着相等的字符串可能不会返回true.要避免此问题,请始终使用.equals()来比较字符串.
其次,请记住,if语句是按指定的顺序检查的.既然你想首先检查空字符串,你应该把它放在最前面.
第三,你必须在所有代码路径上返回一些东西.如果所有if语句都为false,则不返回任何内容.如果添加,else return a + b;您应该获得所需的行为.
此外,我建议采用略有不同的方法:
public static String conCat(String a, String b) {
//If either String is empty, we want to return the other.
if (a.isEmpty()) return b;
else if (b.isEmpty()) return a;
else {
//If the last character of a is the same as the first character of b:
//Since chars are primitives, you can (only) compare them with ==
if (a.charAt(a.length()-1) == b.charAt(0))
return a + b.subString(1);
//Otherwise, just concatenate them.
else
return a + b;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,您可以省略else块,因为return它将结束方法的执行,因此这也将起作用:
public static String conCat(String a, String b) {
if (a.isEmpty()) return b;
if (b.isEmpty()) return a;
if (a.charAt(a.length()-1) == b.charAt(0)) return a + b.subString(1);
return a + b;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
305 次 |
| 最近记录: |