I am evaluating user inputs as commands for my application. If the user presses Q, or q, and then hits enter, the application quits and execution terminates.
是否有适当的背景或最佳实践来说明如何做到这一点?我没有任何资源可以释放,或者类似的东西。我应该只使用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)
很好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)