Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
    
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
add comment

2 Answers

up vote 1 down vote accepted

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.

share|improve this answer
add comment

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).

share|improve this answer
    
could you elaborate? –  Exikle Mar 30 '13 at 3:11
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.