# Inputting Only Alphabetical Input - Slick2D

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?

• 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 – cppanda Mar 29 '13 at 14:49

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.

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()) {

• 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) – Mario Mar 30 '13 at 8:40