What is an appropriate way to programmatically exit an application?

后端 未结 6 1567
慢半拍i
慢半拍i 2021-01-26 17:57

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 terminate

6条回答
  •  滥情空心
    2021-01-26 18:14

    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();
        }
    

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

提交回复
热议问题