因此,我尝试通过阅读填充数据的文本文件来模拟一个非常基本的搜索引擎,然后让用户使用某些关键字搜索文件,然后使用哪个"网站"包含在该文本文件中的包含该关键字的文件将返回给用户。到目前为止,我的代码可以读取文本文件(据我所知),但无论输入的关键字如何,控制台几乎总是声明没有找到结果(文本文件不包含关键字)谢谢大家。
以下是相应的代码:
package myquery;
import java.util.Scanner;
import java.util.*;
import java.io.*;
public class MyQuery{
public static void main(String[] args){
Hashtable<String, ArrayList<String> > hash = new Hashtable<String, ArrayList<String> >();
Scanner input = new Scanner(System.in);
System.out.println("Here is where your .txt file(s) should be located for this program to work properly:");
System.out.println(new java.io.File("").getAbsolutePath());
System.out.println("\nEnter the filename that you want to Search values for. For example \"MyQuery.txt\"");
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(input.nextLine()));
System.out.println("The file was found :) Here are the contents:");
while(reader.ready())
{
String currentline = reader.readLine();
String[] result = currentline.split("\\s");
for(int i = 0; i < result.length; i++)
{
if(!hash.containsKey(result[i]))
{
ArrayList<String> temp = new ArrayList<String>(1);
temp.add(currentline);
hash.put(result[i], temp);
}
else
{
ArrayList<String> temp = (ArrayList<String>)hash.get(result[i]);//
temp.add(currentline);
}
}
}
}
catch(Exception e)
{
System.out.println("Your file was not found unfortunately. Please try again.");
System.exit(1);
}
System.out.println(hash);
do
{
System.out.println("Enter a key to search for the value it is associated with.\n");
System.out.println(hash.get(input.nextLine()));
System.out.println("\nWant to try again? If so, press return and then follow the prompt. Type \"-1\" to quit");
}
while(!input.nextLine().equals("-1"));
try
{
reader.close();
}
catch(Exception e)
{
System.out.println(e);
System.exit(1);
}
}
}
文本文件中一行的示例:
www.Mets.com, "The New York Mets", baseball, team, NY
以下是该计划应如何回应的示例:
Enter a key to search for the value it is associated with.
Mets
www.Mets.com The New York Mets
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit
但这就是我所得到的:
Enter a key to search for the value it is associated with:
Mets
null
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit
虽然。如果我输入一个与第一个/最后一个词之外的任何单词匹配的单词,它就会起作用。
例如
Enter a key to search for the value it is associated with:
New
[www.Mets.com, "The New York Mets", baseball, team, NY, www.nytimes.com, "The New York Times", news]
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit