所以我的代码是用于家庭作业的,用户输入一个句子(字符串),我需要搜索字符串并返回最小的单词。但是,必须在字符串的第一个位置输入一个数字。例如:“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]);
}
最佳答案
在您的 for
循环中(应该从 i = 0
开始),添加如下代码:
try {
double value = Double.parseDouble(myWords[i]);
} catch (NumberFormatException e) {
// add the rest of your code here
}
想法是尝试将单词转换为数字,如果失败,则意味着它不是数字,因此您可以在单词上使用长度逻辑。
关于java - 细化代码。搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12342360/