在java字符串数组中找到最短的单词

Ben*_*iss 3 java debugging

我试图编写一个代码来接受一组单词,并返回字符长度中的最小单词.很简单,出于某种原因,当有一个较短的单词时,它会返回'bye',例如'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
Run Code Online (Sandbox Code Playgroud)

Psh*_*emo 6

compareTo 不比较字符串的长度,但它们的字母顺序.

你应该改变你的状况if (SA[i].length()<first.length()).