ユーザーが入力した文字列で最小の単語を見つけようとしています。これは私がこれまでに持っているものです:
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
が、文字列の最初の単語が表示されるだけです。何か案は?