【发布时间】:2018-03-31 18:02:51
【问题描述】:
我能够在文本文件中找到最长的单词,现在我正在努力逐字查找最长的句子。该算法类似于搜索最长的单词吗? 这是我查找最长单词的代码:
public static int getLongestWord() throws FileNotFoundException {
String longestWord = "";
String current;
Scanner scan = new Scanner(new File("t1.txt"));
while (scan.hasNext()) {
current = scan.next();
if (current.length() > longestWord.length()) {
longestWord = current;
}
}
scan.close();
return longestWord.length();
}
更新! 谢谢您的帮助。我能够得到最长的单词,现在我正在计算最长句子中的单词数。不知何故,柜台有点不对劲。 这是我所拥有的:
public static String getLongestSentence() throws FileNotFoundException {
int numWords = 0;
String longestSentence = "";
String currentSentence = "";
Scanner scan = new Scanner(new File("t1.txt"));
while (scan.hasNext()) {
currentSentence = getNextSentence(scan);
if (currentSentence.length() > longestSentence.length()) {
longestSentence = currentSentence;
}
}
scan.close();
String[] wordList = longestSentence.split("\\s+");
numWords += wordList.length;
System.out.println(longestSentence);
System.out.println("Number of words in this sentence: " + numWords);
return longestSentence;
}
private static String getNextSentence(Scanner scan) {
String sentence = "";
while (scan.hasNext()) {
sentence += " " + scan.next();
if (sentence.contains("."))
break;
}
return sentence;
}
我的文本文件中最长的句子包含 30 个单词,但我的计数器减 1,表示它有 31 个单词。知道为什么吗?谢谢。
【问题讨论】:
-
您应该将文件打开代码与最长单词查找代码分开。
-
好的!感谢您的提示!
-
算法类似吗?好吧,保存当前最长并用新的最长替换它的概念是相同的。显然,检测哪个是最长的代码会有所不同。
-
对。我正在考虑将整个句子存储到 arrayList 中,并创建一个 for 循环来查找最长的句子。这是一个好主意吗?我怎么能用单词而不是字符来计数?