在 java 的文本文件中搜索字符串时遇到问题

Trouble in searching string in an text file in java

我已经编写了在文本文件中搜索字符串的代码。这是我到目前为止尝试过的代码。

import java.io.*;
import java.util.*;

public class testing 
{
    public static void main(String arg[])
    {

    try{
        Scanner scanner=new Scanner("demo.txt");
        List<String> list=new ArrayList<>();

        while(scanner.hasNextLine()){
            list.add(scanner.nextLine()); 
        }

        if(list.contains("Boys"))
        {
            System.out.print("found");
        }
        else
        {
            System.out.print("Not found");
        }
    }
    catch(Exception e)
    {
        System.out.print(e);
    }
}
}

我已经阅读了很多问题,但这些问题并没有为我提供解决方案。此代码搜索给定的字符串和 returns "not found" 即使该字符串存在。

要搜索的文本文件是,

1.  SPINAL ANESTHESIA AGENTS
 "Little Boys Prefer Toys":
Lidocaine
Bupivicaine
Procaine
Tetracaine


2.  XYLOCAINE: WHERE NOT TO USE WITH EPINEPHRINE
 "Nose, Hose, Fingers and Toes"
 Vasoconstrictive effects of xylocaine with epinephrine are helpful in
providing hemostasis while suturing. However, may cause local ischemic necrosis
in distal structures such as the digits, tip of nose, penis, ears.


3.  GENERAL ANAESTHESIA: EQUIPMENT CHECK PRIOR TO INDUCING 
“MALES”
Masks
Airways
Laryngoscopes
Endotracheal tubes
Suction/ Stylette, bougie

任何人都可以建议我可以在此代码中进行哪些更改吗?这段代码有什么问题?

您的代码在列表中搜索不存在的元素 "Boys"。你有其他更长的字符串。解决方案是检查每个字符串是否包含所需的单词

try{
        Scanner scanner=new Scanner("demo.txt");
        List<String> list=new ArrayList<>();

        while(scanner.hasNextLine()){
            list.add(scanner.nextLine()); 
        }

        boolean has = false;
        for (String str : list) {
            if (str.contains("Boys")) {
                has = true;
                break;
            }
        }
        if (has) {
            System.out.print("found");
        } else {
            System.out.print("Not found");
        }
    }
    catch(Exception e)
    {
        System.out.print(e);
    }

如果搜索是您唯一想做的事情,请不要使用列表

而不是:

if(list.contains("Boys"))

使用:

for (String line : list) {
    if(line.contains("Boys")) {
        System.out.println("Line is " + line);
        break;
    }
 }

您正在做的是查找列表是否包含字符串 "Boys" - 但您实际上应该检查的是列表是否有包含术语 "Boys" 的行。由于您一次将文本文件的一行添加到列表中,并且其中一行包含此搜索词,因此您必须从列表中检索每个条目,然后检查字符串以查看您的搜索词是否存在。改为执行以下操作:

while(String line : list) {
    if(line.contains("Boys")) {
        // Do whatever you need here
    }
}

java 7 解法:

public static void main(String[] args) throws IOException {
    String content = new String(Files.readAllBytes(Paths.get("demo.txt")));
    System.out.println(content.contains("Boys") ? "FOUND" : "NOT FOUND");
}

首先,您正在阅读一行并将其添加到列表中。 并将所有作为单个字符串与 "Boys" 进行比较。 您需要获取列表值(字符串)并将该字符串与您的字符串进行比较。