I am new to Java and very new to the class Scanner
. I am writing a program that asks the user for a word, and then this word is distorted inside the file. Each time a word is found, it is printed on a new line in JOptionPane, as well as in the word before and after it. Everything functions as it should, with two exceptions:
If the searched word is the last word in the file, then a "NoSuchElementException" is thrown.
If the search word appears twice in a row (unlikely, but still a problem that I discovered), it returns it only once. For example, if the search word was "is" and "He said he had enough. He was all night," were sentences in a file, then the output:
he had had
He had been
whereas it should be:
he had had
had had enough.
He had been
I believe that my problem is what I use while(scan.hasNext())
, and in this cycle I use scan.next()
twice. I can’t find a solution for this, though, while retaining what I would like to return to the program.
Here is my code:
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();
}
}
Also, on the side of the note: how can I implement to scan.useDelimeter()
ignore any, question marks, commas, periods, apostrophes, etc.?
source
share