有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使输出在每个循环中打印一次,而不是每次迭代

我有一个类,用于在文件中搜索用户指定的字符串。该类按其应该的方式工作,在包含多行的文件中循环,并打印(如果指定的字符串存在)包含所需字符串的行。我现在遇到的问题是,我的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");
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    在进入循环之前,将布尔标志设置为false

    如果你找到一条线,就把它设为真

    循环完成后,检查标志并根据需要写入消息

    boolean found=false;
    

    内环

    found = true;
    

    外环

    if (!found) {
        // do stuff
    }