如果行包含扫描仪输入,如何使用扫描仪从文本文件返回一行?

时间:2018-05-09 20:02:52

标签: java if-statement while-loop java.util.scanner

我想要保存文本文件中的一行,具体取决于扫描仪的输入是否包含在文本行中。

但是,下面的代码接受所有形式的输入,无论输入是否包含在文本文件中,所以我假设if else语句被完全忽略。我不确定如何解决这个问题,所以任何建议都表示赞赏。

Scanner editScanner = new Scanner(System.in);
String editScannerInput = editScanner.nextLine();
Scanner fileScanner = new Scanner(new File("src/FilmInfo.dat"));
String fileScannerLine = fileScanner.nextLine();


while (fileScanner.hasNext()) {
    if (fileScannerLine.contains(editScannerInput.toLowerCase())) {
        String chosenFilm = fileScanner.nextLine();
        System.out.println(chosenFilm);
    } else {
        System.out.println("Film name is not recognised in your collection, please enter a film name that is in your collection.");
    }
}
}

1 个答案:

答案 0 :(得分:0)

如果我正确理解了这个问题,那么代码的一个问题就是在循环时永远不会更新fileScannerLine变量。这是一个有效的代码片段(稍作修改):

System.out.print("Enter input: ");
Scanner editScanner = new Scanner(System.in);
String editScannerInput = editScanner.nextLine();
System.out.println("");
Scanner fileScanner = new Scanner(new File("src/FilmInfo.dat"));

while (fileScanner.hasNext()) {
    String line = fileScanner.nextLine();
    if (line.contains(editScannerInput.toLowerCase())) {
        String chosenFilm = line;
        System.out.println(chosenFilm);
    } else {
        System.out.println(String.format("The film '%s' is not recognised in your collection, please enter a film name that is in your collection.", line));
    }
}
editScanner.close();
fileScanner.close();

Contrived test file:

1
2
3
11
22
33
111
222
333

输出:

1
The film '2' is not recognised in your collection, please enter a film name that is in your collection.
The film '3' is not recognised in your collection, please enter a film name that is in your collection.
11
The film '22' is not recognised in your collection, please enter a film name that is in your collection.
The film '33' is not recognised in your collection, please enter a film name that is in your collection.
111
The film '222' is not recognised in your collection, please enter a film name that is in your collection.
The film '333' is not recognised in your collection, please enter a film name that is in your collection.

此解决方案将遍历文件的所有行并打印出每个匹配项。如果您要查找一个匹配项或将所有匹配项存储在列表中,则可以轻松修改代码以执行此操作。

相关问题