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

2012/5/28

Lists, am I doing it right?

darkmist255 darkmist255

2012/5/28

#
I know there are many ways to get things done in a coding environment, but I'm wondering if what I'm doing follows logic. I have a small section of code I'll copy as an example for how I go about declaring a list of objects:
    List keysToCheck = new ArrayList();

... addedToWorld(World world)
{
        keysToCheck.add("1");
        keysToCheck.add("2");
        keysToCheck.add("3");
        keysToCheck.add("4");
        keysToCheck.add("5");
        keysToCheck.add("6");
        keysToCheck.add("7");
        keysToCheck.add("8");
        keysToCheck.add("9");
        keysToCheck.add("0");
}
Is there another form of doing this or am I along the right line of thinking?
danpost danpost

2012/5/28

#
That could be one way. If you are looking for keystrokes (not just whether the key is down or not; but what key was actually pressed AND released), you could use:
String key = Greenfoot.getKey();
if (key != null)
{
    if ("0123456789".indexOf(key) >= 0) // then it is one of those keys
    if ("abcdefghjkl ...<etc>").indexOf(key) >=0) // then is is one of those keys
Thereby, checking many keys at once. If your checking for keys being held down, then you are definitely on the right track (as they need to be checked individually)!
danpost danpost

2012/5/28

#
Of course, you could use:
String keys = "1234567890";
for (int i = 0; i < keys.length(); i++) keysToCheck.add("" + keys.charAt(i));
in place of lines 5 through 14. You could add other keys to the string in the first line (letter or punctuation). For the other keys (that return Strings larger than one character in length), you could create an array of Strings and use another 'for' loop to add those keys.
darkmist255 darkmist255

2012/5/29

#
That second post looks great (I'll try to remember that for the future) but for the moment I like the idea of keeping track of the key positions themselves. Thanks very much though, keystroke checking should be much easier now :D.
You need to login to post a reply.