我试图在用户输入的字符串中找到最小的单词。这是我到目前为止所拥有的:
import java.util.*;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String myText = sc.next();
String[] myWords = myText.split(" ");
int shortestLength,shortestLocation;
shortestLength=(myWords[0]).length();
shortestLocation=0;
for (int i=1;i<myWords.length;i++) {
if ((myWords[i]).length() < shortestLength) {
shortestLength=(myWords[i]).length();
shortestLocation=i;
}
}
System.out.println(myWords[shortestLocation]);
}
如果我输入"SMALLEST WORD SHOULD BE A"
了,输出应该是A
,但它只是给了我字符串的第一个单词。有任何想法吗?