したがって、私が持っているコードは、ユーザーが文(文字列)を入力し、文字列を検索して最小の単語を返す必要がある宿題用です。ただし、文字列の最初の場所に数字を入力する必要があります。例:「4これは何ですか」。出力は「IS」であり、数値を無視する必要があります。番号を無視する方法を理解する唯一の方法は、番号がある最初のスポットをループでスキップすることです。それはそれ自体で動作しますが、プログラムの残りの部分に入れると動作を停止します。このプログラムをよりクリーンにする方法はありますか?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Lexicographically smallest word
String TheSentence = sc.nextLine();
String[] myWords = TheSentence.split(" ");
int shortestLengths, shortestLocation;
shortestLengths = (myWords[1]).length();
shortestLocation = 1;
for (int i = 1; i < myWords.length; i++) {
if ((myWords[i]).length() < shortestLengths) {
shortestLengths = (myWords[i]).length();
shortestLocation = i;
}
}
System.out.println(myWords[shortestLocation]);
}