I have a textfile like:
fruits bananna blackbery apple
vegetable carrot potato
cars toyota honda ww bmw
I need my Java program to take a string like vegetable and display the next words in line. In this case the program will display carrot potato
I have the code below:
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));
}
The problem is, when I type fruits the program will display all the words from textfile except first word of each line
bananna blackbery apple carrot potato toyota honda ww bmw
, and I want to show me the words that follow the word that I give, in this case would be
bananna blackbery apple
What am I doing wrong?
You need to declare/define your ArrayList within the while loop while (line != null) {.
Reason being once you start adding the data to this list, it would accumulate till the end of your file which you do not want. Instead you just want it to hold the values for the current line only.
Hence,
while (line != null) {
ArrayList<String> lemmes = new ArrayList<String>();
...
Should get you the desired results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With