以编程方式退出应用程序的适当方法是什么? [英] What is an appropriate way to programmatically exit an application?

查看:123
本文介绍了以编程方式退出应用程序的适当方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在评估用户输入作为我的应用程序的命令。如果用户按 Q q ,然后按Enter键,应用程序退出并执行终止。

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); ?有没有推荐的方法呢?

Is there a proper context, or best practices on how to do that? I do not have any resources to release, or anything like that. Should I just use System.exit(0);? Is there a recommended way to do that?

作为我的第一种方法,我会这样做:

As my first approach I do something like this:

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()并从那里返回。

You might as well return up to main() and return from there.

    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)没问题。

But if you don't have anything to release, System.exit(0) is fine.

这篇关于以编程方式退出应用程序的适当方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆