0

I am making a string array so user can type whatever they want.
the problem the code i have below user can enter &, alt, up, @, in string array.
I want user to enter letters and numbers only, and 1st char has to be letter. I couldnt find any method for it.

int z = 0;
String username[] = new String[3];

public void keyPressed(KeyEvent e)
    {
        int keys = e.getKeyCode();

        username[z] = KeyEvent.getKeyText(keys);
        e.consume();                  
    }

public void keyReleased(KeyEvent e)
{ 
    int keys = e.getKeyCode();

    z++;
    e.consume(); 
}
2
Contributors
1
Reply
17
Views
4 Years
Discussion Span
Last Post by stultuske
0

check whether z is 0, if so, and your 'keys' is not a letter (it might come in handy to use the getKeyChar() method instead of the getKeyCode() method)

so ... if this char is not a letter, don't add it to username, don't increase the value of z and call the consume method (don't call this method by default).

also, just using the keyReleased method will help, too. there's no reason to split the code up in several methods. further more, keyPressed might run more then once, making your code less efficiënt.

a bit the same for your second requirement.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.