gpt4 book ai didi

java - 使用HashMap和List解析文本文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:47:34 26 4
gpt4 key购买 nike

我有一个像这样的文本文件:

fruits bananna blackbery apple
vegetable carrot potato
cars toyota honda ww bmw

我需要我的 Java 程序接受一个像 vegetable 这样的字符串并显示一行中的下一个单词。在这种情况下,程序将显示 carrot potato

我有下面的代码:

public static void ParseWithHashMap(String wordGiven) throws IOException {

HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> lemmes = new ArrayList<String>();

FileInputStream fin = null;
InputStreamReader isr = null;
BufferedReader br = null;

try {
fin = new FileInputStream("test.txt");
isr = new InputStreamReader(fin, "UTF-8");
br = new BufferedReader(isr);
String line = br.readLine();

while (line != null) {
String[] toks = line.split("\\s+");

for (int i = 1; i < toks.length; i++) {
lemmes.add(toks[i]);

}
map.put(toks[0], lemmes);
line = br.readLine();

}
} finally {

}

System.out.println(map.get(wordGiven));
}

问题是,当我键入 fruits 时,程序将显示文本文件中除每行的第一个单词之外的所有单词

bananna blackbery apple carrot potato toyota honda ww bmw

,我想显示我给出的单词后面的单词,在这种情况下是

bananna blackbery apple

我做错了什么?

最佳答案

您需要在 while 循环 while (line != null) { 中声明/定义您的 ArrayList

原因是一旦您开始将数据添加到此列表,它就会累积到您不想要的文件末尾。相反,您只希望它只保存当前行的值。

因此,

  while (line != null) {
ArrayList<String> lemmes = new ArrayList<String>();
...

应该能让您得到想要的结果。

关于java - 使用HashMap和List解析文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21889469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com