我已经编写了在文本文件中搜索字符串的代码。这是我到目前为止尝试过的代码。
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/