I want to allow multiple pairs (key, value) to be entered into a dictionary, in Java, from values entered by the user. I made a loop for
to try to insert, but I could not, because every time a new pair (key, value) is inserted, it overwrites the previous one. Is it possible to do that? Allow multiple entries in this dictionary?
The code below creates the phoneBook
dictionary and adds, or at least tries, new pairs, through the variables name
and phone
.
Map<String, Integer> phoneBook = new HashMap<String,Integer>();
int i, phone = 0;
String name = " ", phoneNumber = " ";
int n = reading.nextInt(); // Quantidade de casos de teste
for(i = 0; i < n; i++){
name = reading.next();
phone = reading.nextInt();
phoneBook.put(name, phone);
}
This part inserts a new String
that will allow a search to take place. If the value is found, it prints, or at least should, the values queried by the user:
while(reading.hasNext()){
String s = reading.next();
if(phoneBook.containsKey(s)){
System.out.println(s + "=" + phoneBook.get(name));
} else{
System.out.println("Not Found");
}
}
Input and output examples
It starts with entering an integer for the number of test cases, followed by the user inputs, then moves on to the search. If the value is found, it is printed. If it is not, a message with "Not Found" will be displayed:
Entry
3
Van 99995555
Fernando 11115555
Marilia 66668888
Van
Emilly
Marilia
Expected Exit:
Van=99995555
Not Found
Marilia=66668888
Only the output does not go as expected, it always returns the last number added when the key is found in the dictionary:
Van=66668888
Not Found
Fernando=66668888
Can anyone help me with this? Right away, thank you!