1
\$\begingroup\$

I'm trying to obtain the user input for when they enter their own name. However I would prefer to have it Alphabetically.

This is what I'm doing at the moment:

    if (input.isKeyDown(Input.KEY_A)) {

    }
    if (input.isKeyDown(Input.KEY_B)) {

    }
    if (input.isKeyDown(Input.KEY_C)) {

    }
    //continued for each letter.

Is there an easier way to obtain the input? An hopefully make sure its only alphabetical?

\$\endgroup\$
1
  • \$\begingroup\$ i only develop games in c# and c++, so i can't post this as a real answer as it might be an inefficient solution: make a keylistener, and on the keypress/keydown event, check with .getKeyChar \$\endgroup\$
    – cppanda
    Mar 29, 2013 at 14:49

2 Answers 2

1
\$\begingroup\$

The Java Character class has a simple isLetter function.

The easiest way to handle key presses is to create a class that implements the KeyListener class. A little example would be:

public class MyKeyListener implements KeyListener {

     @Override
     public void keyPressed(int key, char c) {
         if(Character.isLetter(c)) {
             //do letter stuff

         } else {
             //do other stuff
         }
     }

     @Override
     public void keyReleased(int key, char c) {
         //do released key stuff
     }
}

Create an instance of MyKeyListener and then use input.addKeyListener(myKeyListenerInstance) to add the listener to your input.

\$\endgroup\$
0
\$\begingroup\$

Make an input handler class which stores the result of your key strokes then filter what you need using a regex.

A simple [a-zA-Z] will do the job.

Edit: You make a method which you call each tick that stores the current keys as an array

public List<char> pollInput() {
    List<char> keys = new ArrayList<char>;
    while (Keyboard.next()) {
        keys.add((char)Keyboard.getEventKey());
    }
    return keys;
}

Then you convert the list to an array and to a string which you pass through a regex. (Sorry i'm typing on a phone so i'm doing this all from memory).

\$\endgroup\$
2
  • \$\begingroup\$ could you elaborate? \$\endgroup\$
    – Exikle
    Mar 30, 2013 at 3:11
  • \$\begingroup\$ Alex' idea is essentially adding whatever the player typed to your name (temporary). Once that's done, you can use a regular expression to match (and remove) all characters not fitting your filter. The following line should do the trick, although this is Javascript, but I guess it would work in Java as well: name.replace(/[^A-Za-z]+/, ''); (assuming name is the name stored as a string) \$\endgroup\$
    – Mario
    Mar 30, 2013 at 8:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .