Search code examples
javabluej

How do I kick out of a running program?


How do I assign a variable to the ESC. key so that when it is pressed the program is shutdown? I am doing a calculator and the only way that I have seen is doing it directly like:

Scanner console = new Scanner(System.in); 
int x = 1;
while(x==1)
{...
System.out.println("Enter in -1 to exit program");
x = nextInt();
}

I don't know if it is possible to assign, per say a -1 to the escape key. Let me know if you have any ideas? It would be astronomically appreciated. ;-) ... :-)


Solution

  • Unfortunately, you can't.

    ESC can't be read by the Scanner. You are supposed to use a key listener by a UI library (for instance, Swing). Have a look at "How to write a key listener?".

    In this case, you should ask for a number from a user which is a key of the loop break (like you actually did).