Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding the shortest word in an array of strings java

Tags:

java

debugging

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
like image 312
Benji Weiss Avatar asked Dec 12 '22 03:12

Benji Weiss


1 Answers

compareTo doesn't compare length of Strings, but their alphabetic order.

You should change your condition to if (SA[i].length()<first.length()).

like image 93
Pshemo Avatar answered Dec 21 '22 23:12

Pshemo