I am currently trying to Print A selected Word from my HashMap to screen.The output correct the first time, however each time after it gives the first value, can anyone see what I am doing wrong?
public void searchIndex() throws FileNotFoundException, IOException {
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter a word to search");
String entry = sc.nextLine().toLowerCase();
String key = null;
String value = null;
Set<Integer> indices = null;
for (String search : index.keySet()) {
for (WordEntry values : index.values()) {
key = search;
value = values.getDefinition();
indices = values.getIndices();
}
}
System.out.println("Word " + key + " And " + value + indices);
System.out.println("Do you wish to continue searching,'Yes' if so");
String answer = sc.nextLine();
if (answer.equalsIgnoreCase("Yes")) {
searchIndex();
Output: Please Enter a word to search
yellow
Word yellow And color
Do you wish to continue searching,'Yes' if so
yes
Please Enter a word to search
open
Word yellow And color
Do you wish to continue searching,'Yes' if so
In this block:
for (String search : index.keySet()) {
for (WordEntry values : index.values()) {
key = search;
value = values.getDefinition();
indices = values.getIndices();
}
}
You are setting the values of key
, value
, and indices
unconditionally .
This means that whatever your input is, it will always set :
key
to the last key in index
. value
to the definition of the last value in index
. indices
to the last indices of the last value in index
. And, I guess that Yellow is the last item in index
. Hence you get the said output.
I think you need to set the values of key
, value
, and indices
according to some condition based on the input.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.