在Java中查找字符串中的最小单词

Eri*_*ric 1 java string

我正在尝试在用户输入的字符串中找到最小的单词.这是我到目前为止:

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]);
}
Run Code Online (Sandbox Code Playgroud)

如果我输入"SMALLEST WORD SHOULD BE A",输出应该是,A但它只是给我字符串的第一个单词.有任何想法吗?

Joã*_*lva 5

你的算法很好,但不是使用next():

String myText = sc.next();
Run Code Online (Sandbox Code Playgroud)

这将只读取一个令牌,即第一个单词,use nextLine(),它将读取整行:

String myText = sc.nextLine();
Run Code Online (Sandbox Code Playgroud)