Similar code, yet one version does not return a String when it should

Patricia Manarazan :

For a class exercise, both my friend and I wrote a similar code. Hers works while mine gives out:

Error: This method must return a result of type java.lang.String

Her code :

 public static String alphaString (String a, String b) {

    for (int i=0; i<a.length(); i++){
      if ((int)(a.charAt(i)) < ((int)(b.charAt(i)))) {
        return a;
      }
      if ((int)(a.charAt(i)) > ((int)(b.charAt(i)))) {  
        return b;
      }
    }

    return ("these are the same words") ;

  }

My code :

// method that takes two Strings and returns the one that comes first in the alphabet

// alphaString("banana", "apple")--> "apple"

// alphaString("snake", "squirrel")--> "snake".

public static String alphaString(String s1, String s2) {


for (int i = 0; i<s1.length(); i++ ) {
    if (s1.charAt(i)<s2.charAt(i)) {
        return s1;
    }
    if (s1.charAt(i)>s2.charAt(i)){
        return s2;

    }


}

Now, I can tell that our variables are named differently and that she uses (int) (though I don't think it is necessary). I don't understand why her code works and mine not. If I try to also add the (int) and make the code even more similar, I still get the error.

Does anyone have any idea why that might be?

Elliott Frisch :

You seem to be missing the default return of "these are the same words". It isn't clear why you both chose to implement this with a loop (or why neither of you chose to use an else). Regardless, String is Comparable so I would simply do

public static String alphaString(String s1, String s2) {
    int c = s1.compareTo(s2);
    if (c < 0) {
        return s1;
    } else if (c > 0) {
        return s2;
    }
    return "these are the same words";
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=96066&siteId=1