【发布时间】:2015-10-30 18:16:38
【问题描述】:
我是 Java 新手,对 Scanner 类非常陌生。我正在编写一个程序,它要求用户输入一个单词,然后在文件中搜索这个单词。每次找到该单词时,它都会打印在 JOptionPane 中的新行上,以及它之前和之后的单词。一切正常,但有两个例外:
如果要搜索的单词恰好是文件中的最后一个单词,则会引发“NoSuchElementException”。
-
如果正在搜索的单词连续出现两次(不太可能,但我发现仍然是一个问题),它只会返回一次。例如,如果要搜索的单词是“had”,“He said that he had enough. He had been up all night”是文件中的句子,那么输出是:
he had had He had been应该是这样的:
he had had had had enough. He had been
我相信我的问题在于我使用了while(scan.hasNext()),并且在这个循环中我使用了两次scan.next()。虽然我找不到解决方案,但仍然可以实现我希望程序返回的内容。
这是我的代码:
//WordSearch.java
/*
* Program which asks the user to enter a filename followed
* by a word to search for within the file. The program then
* returns every occurrence of this word as well as the
* previous and next word it appear with. Each of these
* occurrences are printed on a new line when displayed
* to the user.
*/
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class WordSearch {
public static void main(String[] args) throws FileNotFoundException {
String fileName = JOptionPane.showInputDialog("Enter the name of the file to be searched:");
FileReader reader = new FileReader(fileName);
String searchWord = JOptionPane.showInputDialog("Enter the word to be searched for in \"" + fileName + "\":");
Scanner scan = new Scanner(reader);
int occurrenceNum = 0;
ArrayList<String> occurrenceList = new ArrayList<String>();
String word = "", previousWord, nextWord = "", message = "", occurrence, allOccurrences = "";
while(scan.hasNext()){
previousWord = word;
word = scan.next();
if(word.equalsIgnoreCase(searchWord)){
nextWord = scan.next();
if(previousWord.equals("")){
message = word + " is the first word of the file.\nHere are the occurrences of it:\n\n";
occurrence = word + " " + nextWord;
}
else{
occurrence = previousWord + " " + word + " " + nextWord;
}
occurrenceNum++;
occurrenceList.add(occurrence);
}
}
for(int i = 0; i < occurrenceNum; i++){
allOccurrences += occurrenceList.get(i) + "\n";
}
JOptionPane.showMessageDialog(null, message + allOccurrences);
scan.close();
}
}
另外,附带说明:如何实现 scan.useDelimeter() 以忽略任何问号、逗号、句点、撇号等?
【问题讨论】:
-
我可以建议你把它分解成多个函数吗?
-
是的,我打算这样做,然后再清理它。
-
.... 在我们都必须通读它之后。请注意,将代码分解为函数通常可以帮助您发现此类问题。