0

Java: Below I have Written a code in which if user enter escape key then the loop has to be terminate..but it doesn't work on escape key

Code

import java.util.Scanner;

public class While { 
 public static void main(String args[]){
     
     Scanner scan = new Scanner(System.in);
     
     char ch=' ';
     
     while (ch!=27){  // 27 is ASCII code For 'Escape' Key.
         
         System.out.println("Input Any Character ");
          ch =scan.next().charAt(0);
         
     }
     System.out.println("End of Loop");
     
 }
}
  • It's not possible. scanner reads lines at a time, not single keystrokes. Make a GUI or web app. – rzwitserloot Aug 18 '20 at 16:27
  • Does this answer your question? [break a loop if Esc was pressed](https://stackoverflow.com/questions/10736226/break-a-loop-if-esc-was-pressed) – Zaid Shawahin Aug 18 '20 at 17:14

1 Answers1

1

Already been asked before, this is one of the useful answers:

"You're currently making a command-line application which reads stuff from standard input and prints stuff to standard output. How buttons presses are handled depends entirely on the terminal in which you are running your program, and most terminals won't send anything to your application's stdin when escape is pressed.

If you want to catch key events, you'll have to make a GUI application using AWT or Swing. If all you want is to terminate your program while it's running, try pressing Ctrl+C (this works in most terminals)."

Zaid Shawahin
  • 355
  • 2
  • 18