This site requires JavaScript, please enable it in your browser!
Greenfoot back
Psychpsyo
Psychpsyo wrote ...

2016/8/7

Checking if an array contains a string

Psychpsyo Psychpsyo

2016/8/7

#
So I wrote this method today to check if my array contains the currently pressed key:
1
2
3
4
5
6
7
8
public boolean arrayContains(String S, String[] A) {
        for(int i = 0; i < A.length; i++) {
            if(A[i] == S) {
                return true;
            }
        }
        return false;
    }
and used it in this if:
1
if(arrayContains(Greenfoot.getKey(), validChars)) {}
The validChars array looks like this:
1
String[] validChars = {" ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
My problem is: It simply doesn't work and I have no idea, why.
danpost danpost

2016/8/7

#
I believe the main problem resides with line 3. The String object returned by 'getKey' is not the same String object contained within the array; so comparing the two will result in 'false' -- they are not the same object. To compare the contents of the objects, you need to use the 'equals' method on the one String object you know to exist (the value of 'S', which is received by the call to 'Greenfoot.getKey()' could be 'null' and calling any method on a 'null' value will result in a NullPointerException):
1
if (A[i].equals(S) {
Psychpsyo Psychpsyo

2016/8/8

#
changed line 3 to this now:
1
if(A[i].equals(S)) {
But it still doesn't work.
danpost danpost

2016/8/8

#
I tested it out, and it works properly. I can think of only two reasons why it may not be working for you. The first is if you are using 'Greenfoot.getKey()' multiple times within the same act cycle. The other is if you never added any code between the squiggly brackets at the end of this line:
1
if(arrayContains(Greenfoot.getKey(), validChars)) { < here > }
Oh, and since the 'arrayContains' method only returns a true/false value, the actual keystroke is not retainable as coded. You could try:
1
2
String key = Greenfoot.getKey();
if (arrayContains(key, validChars)) { System.out.println(key); }
for testing. I would code it differently, however. I would consider this way:
1
2
String key = Greenfoot.getKey();
if (key != null && " 1234567890".indexOf(key) >= 0) { System.out.println(key); }
eliminating the need for the extra 'arrayContains' method.
You need to login to post a reply.