I have a class that is designed to search a file for a user-specified string. The class works as it should, cycling through a file containing multiple lines and printing - provided the specified string exists - the line(s) containing the desired string. The issue I'm having at the moment is that my else statement (provide new word if previous word does not exist) runs for every line (as it should), but I only want it to run once per loop. Here is my code
public class SimpleDBSearch {
public void sdbSearch(Scanner searchWord) throws IOException{
//Prompt user for input
System.out.println("Please input the word you wish to find:");
//Init string var containing user input
String wordInput = searchWord.next();
//Specify file to search
File file = new File("C:/Users/Joshua/Desktop/jOutFiles/TestFile.txt");
//Init Scanner containing specified file
Scanner fileScanner = new Scanner(file);
//Loops through every line looking for lines containing previously specified string.
while(fileScanner.hasNextLine()){
String line = fileScanner.nextLine();
if(line.contains(wordInput)){ //If desired string is found, print line containing it to console
System.out.println("I found the word you're looking for here: " + line);
}else{ //If desired string not found, prompt user for new string. I want this to occur only once, not per every line-check
System.out.println("Please input a new word");
}
}
}
Set a boolean flag to false before entering the loop.
If you find a line set it to true.
Once the loop has finished check the flag and write the message as appropriate.
boolean found=false;
Inside loop
found = true;
Outside loop
if (!found) {
// do stuff
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments