2015-11-11 161 views
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"); 
     } 
    } 
} 

回答

2

在進入循環之前將布爾標誌設置爲false。

如果您發現一條線將其設置爲true。

循環完成後,檢查標誌並根據情況編寫消息。

boolean found=false; 

內環路

found = true; 

外循環

if (!found) { 
    // do stuff 
} 
+0

你介意張貼各種各樣的標誌的例子嗎?我從來沒有用過,更別說看到他們了 –

+0

查看編輯答案 –

+0

這樣做,非常感謝! –