到目前为止,我已经制作了一个可以在文本文件中搜索单个字符串的程序。它确实给出了我搜索的字符串的索引。但是,如何在单个文本文件中搜索多个字符串?
到目前为止,如果我使用扫描仪输入“Alice”,我的输出将是:
Got a match at line 17
Got a match at line 19
Got a match at line 20
Got a match at line 21
但是,如果可能的话,我如何在我的扫描仪中搜索 Alice、John、Steven 作为我的输入,我的输出如下:
Got a match for Alice at line 17
Got a match at John at line 19
Got a match at Steven at line 20
Got a match at Steven at line 21
.
public static void main(String[]args) throws IOException{
int nnames;
String[] names;
String stringSearch = null;
Scanner scan = new Scanner(System.in);
//for(int i=1;i<=3;i++){
stringSearch = scan.nextLine();
ArrayList<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("File1.txt"));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}reader.close();
Collections.sort(words);
System.out.println("ArrayList elements after sorting in ascending order : ");
System.out.println("");
for(int i=0; i<words.size(); i++)
System.out.println(words.get(i));
for(String sLine : words)
{
if (sLine.contains(stringSearch))
{
int index = words.indexOf(sLine);
System.out.println("");
System.out.println("Got a match at line " + index);
}
}
System.out.println(words.size());
}