0

Hi I am new to stackoverflow.com I have been using JAVA recently from programming purposes. I have a code using switch case which works fine. This is the code:-

Scanner s=new Scanner(System.in);
int i=1;
while(i>0)
{
    char key = s.next().charAt(0);
    switch(key)
    {
      case 'w':
        System.out.println("I am moving forward");
        break;
      case 's':
        System.out.println("I am moving backward");
        break;
      case 'd':
        System.out.println("I am moving right");
        break;
      case 'a':
        System.out.println("I am moving left");
        break;
      case 'x':
        i=-1;
        break;
      default:
        System.out.println("Plz give a valid command");
    }
}

But the problem is every time I give an input command I have to press enter so that the program accepts the input. I want a method for which the program should accept the command as soon as I give the input character. Any tips please???

Vasilis G.
  • 6,470
  • 3
  • 15
  • 27
  • 4
    Possible duplicate of [How to read a single char from the console in Java (as the user types it)?](https://stackoverflow.com/questions/1066318/how-to-read-a-single-char-from-the-console-in-java-as-the-user-types-it) – Joe C Jan 28 '18 at 14:03
  • well... That's the way System.in works in java... – Stav Saad Jan 28 '18 at 14:08
  • Read the explanation of this answer here: https://stackoverflow.com/a/13943088/2849346 – MWiesner Jan 28 '18 at 14:09
  • your answer is here - [How do I read input character-by-character in Java?](https://stackoverflow.com/questions/811851/how-do-i-read-input-character-by-character-in-java) – ArifMustafa Jan 28 '18 at 14:11

1 Answers1

1

I think that, you must handle the Keyboard events like keyTyped(KeyEvent e){} instead of Scanner(System.in);. You can do it by implementing the KeyListener interface.

Kenany
  • 356
  • 3
  • 10
  • 1
    Can you please show me an example how to do that? Basically I dont want to create a frame. I simply want to execute the command on pressing the key. Kindly help me with that. – Ronauk Maharana Jan 28 '18 at 18:05