1

I want to write a key listener to listen for only numeric keys. How can I achieve this?

Here's what I've tried:

if (  e.getKeyCode() > 96 & e.getKeyCode() < 106
   || e.getKeyCode() > 47 & e.getKeyCode() < 58)
{
    // do something
}

What is the problem in this code?

Michael
  • 41,989
  • 11
  • 82
  • 128
Alify
  • 59
  • 1
  • 7

1 Answers1

1

Use this one:

if (e.getKeyCode() >= 96 && e.getKeyCode() <= 105 || e.getKeyCode() >= 48 && e.getKeyCode() <= 57){
     // do something
}

Note the difference between & and &&, also fixed the keycode ranges.

Community
  • 1
  • 1
Floris Velleman
  • 4,848
  • 4
  • 29
  • 46