如何在Java中使用Escape键终止While循环?

huangapple go评论82阅读模式
英文:

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)."

huangapple
  • 本文由 发表于 2020年8月19日 00:26:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63472818.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定