Search code examples
javaslick2d

Checking on multiple values in array


I'm currently trying to make a small chatgame in the Slick2d framework. The framework's got a method called

isKeyPressed()

and a whole long list of variables i can use to check. For instance:

input.KEY_A

Currently the only way i can register a letter, is by having a whole list of those checkers:

if (input.isKeyPressed(input.KEY_A)) {
    this.text += "a";
}
if (input.isKeyPressed(input.KEY_B)) {
    this.text += "b";
}
if (input.isKeyPressed(input.KEY_C)) {
    this.text += "c";
}

Is there any smarter way i can do this?

I could imagine i would be able to store the input.KEYS in an array in some way, but i'm not sure if that is a proper way, and even how to implement it.


Solution

  •  Map<Integer,Character> keyWithLetterMap = new HashMap<Integer,Character>();
     //populates initially the map, for instance: keyWithLetterMap.put(input.KEY_A, 'a');
    
     for (Map.Entry<Integer, Character> keyWithLetter : keyWithLetterMap.entrySet()) {
         if(input.isKeyPressed(keyWithLetter.getKey())) 
            this.text += keyWithLetter.getValue();
     }
    

    Otherwise, and even better way, use enum instead of Map ;)