Java如何使给定的片段显示整行,而不仅仅是最后一个单词

Java如何使给定的片段显示整行,而不仅仅是最后一个单词,java,Java,这段代码找到了第一个单词“恐怖”,但没有显示整行内容,只有找到的单词 File f = new File("MyFile.txt"); Scanner scan = new Scanner(f); while (scan.hasNextLine()) { String str = scan.next(); if (str.contains("horror")) { System.out.println(str + "

这段代码找到了第一个单词“恐怖”,但没有显示整行内容,只有找到的单词

File f = new File("MyFile.txt");
Scanner scan = new Scanner(f);
while (scan.hasNextLine()) {
    String str = scan.next();
    if (str.contains("horror")) {
        System.out.println(str + " este horror");
    }
}

为什么会这样?

Scanner类有很多方法可以读取不同的类型,每个方法都有相应的
hasNext…()
方法,例如
nextInt()
hasNextInt()
。您选中了
hasNextLine()
,但使用了返回下一个单词的
next()
,而不是返回下一行的
nextLine()

将代码更改为:

String str = scan.next(); // read next word ❌
致:


Scanner
类有许多用于读取不同类型的方法,每个方法都有相应的
hasNext…()
方法,例如
nextInt()
hasNextInt()
。您选中了
hasNextLine()
,但使用了返回下一个单词的
next()
,而不是返回下一行的
nextLine()

将代码更改为:

String str = scan.next(); // read next word ❌
致:


也许您应该用
String str=scan.nextLine()阅读这行代码
也许你应该用
String str=scan.nextLine()来阅读这行代码向上投票也是因为❌✅ 这也是因为❌✅