在java中搜索文本文件中的字符串时遇到问题
我已经编写了在文本文件中搜索字符串的代码。这是我迄今为止尝试过的代码在java中搜索文本文件中的字符串时遇到问题,java,file,search,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
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);
}
}
}
有人能建议我在这段代码中能做些什么改变吗?这段代码有什么问题吗?您的代码在列表中搜索不存在的元素“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);
}
试试看{
扫描仪=新扫描仪(“demo.txt”);
列表=新的ArrayList();
while(scanner.hasNextLine()){
添加(scanner.nextLine());
}
布尔has=false;
for(字符串str:list){
如果(str.contains(“Boys”)){
has=真;
打破
}
}
如果(有){
系统输出打印(“找到”);
}否则{
系统输出打印(“未找到”);
}
}
捕获(例外e)
{
系统输出打印(e);
}
如果您只想进行搜索,请不要使用列表而不是:
if(list.contains("Boys"))
使用:
您要做的是查找列表中是否包含字符串“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");
}
首先,你要读一行并将其添加到列表中。 并将所有的数据作为一个字符串与“男孩”进行比较。
您需要获取列表值(字符串)并将该字符串与您的字符串进行比较。您应该使用正则表达式。如果找到答案,请接受,SOF将感谢您:)
while(String line : list) {
if(line.contains("Boys")) {
// Do whatever you need here
}
}
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");
}