finding the shortest word in an array of strings java
我正在尝试编写一个代码来接收一组单词,并返回字符长度最小的单词。非常简单,由于某种原因,当其中有一个较短的单词(例如"不")时,它会返回"再见"。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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 |
您应该将您的条件更改为
你的方法很接近,但是你的变量名有点难以阅读开始你只需要调用你的方法一次来打印最短的名字(调用它两次搜索两次,并丢弃第一个结果),
1 2 3 4 |
接下来,测试您的输入是否有效(不是
1 2 3 4 5 6 7 8 9 10 11 12 |
在 Java 8 中,您创建一个
1 2 3 4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.util.Comparator; import java.util.function.Function; import static java.util.Arrays.asList; public class Foo { public static void main(String[] args) { String[] words = {"hello","goodbye","jack","bye","yes","no","yoo"}; System.out.println(shortestWord(words)); } static String shortestWord(String[] words) { return asList(words).stream().min(compareBy(String::length)).get(); } static <A, B extends Comparable> Comparator<A> compareBy( Function<A, B> f) { return (A x, A y) -> f.apply(x).compareTo(f.apply(y)); } } |
我不确定你想用方法 compareTo() 做什么,但是如果你想继续查找字符串的长度,你可以使用 length() 方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class function 2 { public static void main(String[] args) { String [] SA = {"hello" ,"goodbye" ,"jack" ,"bye" ,"yes" ,"no" ,"yoo"}; System.out.println("The shortest word is" + smallest(SA)); } public static String smallest(String SA[]) { //Keep track of the shortest word by index and length int index = 0, minLength = SA[0].length(); for (int i = 1; i < SA.length; i++){ //if the next string is smaller in length then we save that index and length in our variables if(SA[i].length() < minLength){ index = i; minLength = SA[i].length(); } } //returns the smallest word return SA[index]; } } |