为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;
}
}
我不明白为什么Eclipse无法识别String返回。
答案 0 :(得分:6)
首先,您要将字符串与==进行比较,然后通过引用对它们进行比较。这意味着相等的字符串可能不会返回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;
}
}
请注意,您可以省略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;
}
答案 1 :(得分:1)
在这些情况下,该方法不会返回任何内容,即使它应该返回一个String。
添加:
return "";
或
return null;
到您方法的最后,然后重试。