im trying to write a code to take in a group of words, and return the smallest word in character length. pretty simple, for some reason its returning 'bye' when there is a shorter word in there such as 'no'.
public class function2 {
public static void main(String [] args) {
String [] SA = {"hello", "goodbye", "jack", "bye", "yes", "no", "yoo"};
smallest(SA);
System.out.println("The shortest word is " + smallest(SA));
}
public static String smallest(String SA[]) {
String first = SA[0];
for (int i = 1 ; i < SA.length ; i++) {
if ((SA[i].compareTo(first)) < 0) {
first = SA[i];
} // if
} // for
return first;
}// smallest
}// lab1b
compareTo
doesn't compare length of Strings, but their alphabetic order.
You should change your condition to if (SA[i].length()<first.length())
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With