L'utilisation d'une instance d'Iterator semble résoudre le problème.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Stack{
public static void main(String[] args){
//create a hashmap
HashMap<Integer, String> map = new HashMap<Integer,String>();
//populate with dummy out-game entries
for(int i = 0; i < 8;i++){
map.put(i, "OUT-GAME");
}
// add the last two with in-game value
map.put(8, "IN-GAME");
map.put(9, "IN-GAME");
//declare an iterator on map
Iterator it = map.entrySet().iterator();
//number of time "in-game" is encountered
int check = 0;
//while the iterator has more to go
while(it.hasNext()){
//get the key-value pairs and print them just for checking
//the entries
Map.Entry pair = (Map.Entry<Integer,String>) it.next();
System.out.println(pair.getKey() + " " + pair.getValue());
//if the value "in-game" is encountered increment the check by 1
if(pair.getValue().equals("IN-GAME")){
System.out.println("We have a player in game");
check++;
}
//if "in-game" is encountered more than once, then print an alarm
if(check > 1){
System.out.println("More than 1 player in game. There's something wrong");
}
}
//if there's only one player with "in-game", inform me
if(check == 1){
System.out.println("We have exactly one player in the game");
}
}
}
Le code ci-dessus vous informe, il y a plus d'un joueur avec la propriété "in-game" sur.
Avez-vous considéré comme un [ 'Goyave BiMap'] (https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/BiMap.html)? –
@JoeC Je suis encore un peu nonchalant alors je vais regarder ça. Merci. – joeldesante
Une façon d'éviter le problème est d'avoir une variable appelée 'playerInGame'. Ensuite, il ne peut contenir qu'un seul joueur (ou zéro avec 'null'). –