我正在评估用户输入作为我的应用程序的命令。如果用户按 Q 或 q,然后按 Enter 键,应用程序将退出并终止执行。
是否有适当的背景或最佳实践来说明如何做到这一点?我没有任何资源可以释放,或者类似的东西。我应该只使用 System.exit(0);
?有推荐的方法吗?
作为我的第一种方法,我做了这样的事情:
while (true){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//Other logic goes here...
if (br.readLine().equalsIgnoreCase("Q")){
System.exit(0);
}
}
catch (IOException ioe) {
System.out.println("IO error trying to read your selection");
}
}
最佳答案
您不妨返回到 main()
并从那里返回。
private void loop() {
while (true){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//other logic goes here...
if(br.readLine().equalsIgnoreCase("Q")){
return; // You're done and you are returning to the caller.
}
}
catch (IOException ioe) {
System.out.println("IO error trying to read your selection");
}
}
}
public static void main(String[] args) {
loop();
}
但是如果您没有任何要释放的内容,System.exit(0)
就可以了。
关于java - 以编程方式退出应用程序的适当方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1736245/