Reputation: 33
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???
Upvotes: 0
Views: 488
Reputation: 562
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.
Upvotes: 1