java - 在java中搜索文本文件中的字符串时出现问题

标签 java file search

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

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);
    }
}
}

我读过很多问题,但这些问题没有为我提供解决方案。此代码搜索给定的字符串并返回“未找到”,即使该字符串存在。

要搜索的文本文件是,

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);
    }

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

关于java - 在java中搜索文本文件中的字符串时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28883801/

相关文章:

java - 使用 Resteasy/Hibernate/Spring 简化 DAO 层

java - 如何交换 Java 数组中的数据列

java.math.BigDecimal 并不总是适用于保留两位小数?

file - Ant 脚本 : Replace only the value of the key in a java property file

java - 在 Lucene 中查找找到的查询的位置

java - JScrollPane 不会显示在 JTextArea 中

Python:检查给定目录中是否存在任何文件

algorithm - 为速度牺牲准确性的搜索/排序算法

c# - 存储不同语言时如何在sql server中搜索文本

C++ 将格式化数据打印到 std::cout 或文件(缓冲)