0

I'm starting to create game and now I'm testing for player input.

package main;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Game {

    public static void main(String[] args) throws IOException {
        final char[] keyCodesArray = {'w','a','s','d'};

        while(true) {
            char tmp = (char) new InputStreamReader(System.in).read ();
            if(Arrays.asList(keyCodesArray).contains(tmp)) {
                System.out.println("You entered : " + tmp);
            } else {
                System.out.println("Type valid game char");
            }
        }
    }
}

Why, when I press 'w' or 'a', console prints second communicate: "Type valid game char" and not the first one? I searched StackOverflow for an answer but nothing really helped me.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
  • 3
    What do you think the type of `Arrays.asList(keyCodesArray)` is? (Note: It's not `List`) – Andy Turner Jun 16 '17 at 20:02
  • 1
    I would just use a String here "wasd" (and beware with the `new` inside the loop) –  Jun 16 '17 at 20:03
  • I guess this is not a duplicate of the mentioned question. That describes about int/integer. We reach this page by searching (google/stackoverflow). I guess I would not search for "integer" when I get a problem in the "character" datatype. I disagree to close this issue as a duplicate. The root cause is the same, but the issues are different. – smilyface Dec 30 '21 at 11:15

2 Answers2

2

Your current approach is incorrect because when you do Arrays.asList(keyCodesArray) what you're getting is something like this:

List<char[]> 

In order to make Arrays.asList(keyCodesArray) to work properly, you'll need to change this:

final char[] keyCodesArray = {'w','a','s','d'};

to this:

final Character[] keyCodesArray = {'w','a','s','d'};

which essentially provides a List<Character> when you apply Arrays.asList(keyCodesArray), therefore:

if(Arrays.asList(keyCodesArray).contains(tmp)) { ... }

would work.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

You can't use Arrays.asList() to wrap a primitive array. You'll need a custom method to check if a value is contained in the array:

static boolean contains(char[] array, char value) {
    for (char c : array)
        if (c == value)
            return true;
    return false;
}
shmosel
  • 49,289
  • 6
  • 73
  • 138