我有一个dictionaryTXT.txt文件,它存储单词及其含义,例如" apple:a fruit"," cat:a animal"," bat:playing仪器"现在我想从用户那里获取输入并搜索含义。 我无法进行搜索。有人可以帮忙吗?
public static void main (String[] args) throws IOException
{
List<String> lines = new ArrayList<String>();
System.out.println("enter the word you want to search-");
Scanner in= new Scanner(System.in);
String input=in.nextLine();
FileReader fileReader = new FileReader("dictionaryTXT.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
String [] words = lines.toArray(new String[lines.size()]);
StringBuffer result = new StringBuffer();
for (int j = 0; j < words.length; j++)
{
result.append(words[j]);
}
String my = result.toString();
int i = my.indexOf(":");
String sub=my.substring(0,i);
if(sub.equals(input))
{
System.out.println(my);
}
else
{
System.out.println("word not found");
}
bufferedReader.close();
}
}
答案 0 :(得分:2)
使用Map<String, String>
。并使用Files.readAllLines()
:
final Map<String, String> entries = new HashMap<>();
final Path dict = Paths.get("dictionaryTXT.txt");
String[] array;
for (final String line: Files.readAllLines(dict, StandardCharsets.UTF_8)) {
array = lines.split("\\s*:\\s*");
entrues.put(array[0], array[1]);
}
然后搜索一个单词:
final String description = entries.get(input);
if (description == null)
System.out.println("not found");
else
System.out.println("definition: " + description);
当然,如果你的字典特别大,你会想要使用Files.newBufferedReader()
而是逐行阅读。
此外,上面的代码缺少基本的错误检查;运动留给读者
答案 1 :(得分:1)
请考虑使用专门用于查找和检索的Map。
Map<String, String> dictionary = new HashMap<String, String>();
while ((line = bufferedReader.readLine()) != null) {
String[] lineArray = line.split(":");
dictionary.put(lineArray[0].trim(), lineArray[1].trim());
}
Scanner in= new Scanner(System.in);
String input=in.nextLine();
if (dictionary.get(input) != null) {
System.out.println(dictionary.get(input));
}
else {
System.out.println("No definition found");
}
lookup
与search
相比,速度更快,效率更高。