我正在尝试查找用户输入字符串中的最小单词。这是我到目前为止有:在Java中查找字符串中的最小单词
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
,但它只是给我的字符串的第一个字。有任何想法吗?
很高兴你找到了你的答案!记得阅读Javadocs,你会发现你使用了错误的方法:D –