1
我有一個類用於在文件中搜索用戶指定的字符串。該類按照它應該的方式工作,循環遍歷包含多行和打印的文件 - 只要指定的字符串存在 - 包含所需字符串的行。我現在遇到的問題是,我的else語句(如果以前的單詞不存在,則提供新單詞)爲每一行運行(因爲它應該),但我只希望它在每個循環運行一次。這是我的代碼每循環輸出一次打印,而不是每次迭代
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");
}
}
}
你介意張貼各種各樣的標誌的例子嗎?我從來沒有用過,更別說看到他們了 –
查看編輯答案 –
這樣做,非常感謝! –