可能重複:
Using Recursion To Compare Strings To Determine Which Comes First Alphabetically Java編寫一個遞歸方法來比較兩個字符串?
我卡在這個遞歸問題按字母順序排序任何兩個字符串。這裏的方法簽名:
int compareTo(String s1, String s2)
它yeilds:
returnval <0
意味着s1 < s2
returnval ==0
意味着s1 == s2
returnval >0
意味着s1 > s2
這裏是我的代碼:
個package bonushw;
public class Recursion {
public void main (String[] args){
Recursion recurse = new Recursion();
System.out.println("value is: " + recurse.compareTo("bill","bill"));
}
public int compareTo (String s1, String s2) {
if(s1.length() == 0){
return 0;
}
else if (s1.charAt(0) < s2.charAt(0)){
return -1;
}
else if (s1.charAt(0) > s2.charAt(0)) {
return 1;
}
else {
return compareTo(s1.substring(1), s2.substring(1));
}
}
感謝
@AmitBhargava - 我只是說我的代碼,感謝 –
是否與你的代碼有問題嗎?它有什麼問題? –
'compareTo(「」,「Hello World」)的值應該是什麼? – emory