所以我的代码是用于家庭作业,用户输入一个句子(字符串),我需要搜索字符串并返回最小的单词。但是,必须在字符串的第一个位置输入一个数字。例如:“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]);
}