英文:
How to Terminate While Loop through Escape Key in Java?
问题
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");
}
}
英文:
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");
}
}
答案1
得分: 1
[已经在之前的提问中提到过,这是其中一个有用的回答:]
“您目前正在制作一个命令行应用程序,该应用程序从标准输入读取内容并将内容打印到标准输出。按钮按下的处理方式完全取决于您运行程序的终端,大多数终端在按下 escape 键时不会向应用程序的标准输入发送任何内容。
如果您想捕获按键事件,您需要使用 AWT 或 Swing 制作一个 GUI 应用程序。如果您只想在程序运行时终止它,可以尝试按下 Ctrl+C(在大多数终端中都适用)。”
英文:
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)."
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论