How to exit from an endless Java program and print a message?

728 Views Asked by At

Say I have a java program (actually I wrote a CLI) which goes into an endless loop and within that loop it's incrementing a counter. When I hit Ctrl + C from my command line to exit from the program, can I print the value of the counter and then exit? Say I have a function like:

public void count(){
    int count = 1;
    while (count>0) {
        count++;
    }
}

Now, I invoke this bit of code and the execution begins. After a while, I hit Ctrl + C on the terminal and the program is forced to exit. While it exits, can I somehow print the value of count and then exit?

Note: I'm not doing this exactly in my program. I'm just trying to figure out if there's a way I can force exit a program and upon force exit print something to the console.

2

There are 2 best solutions below

1
On BEST ANSWER

Slight copy pasta from another site (StackOverflow prefers answers here though)

public class Main {
  public static var message; //can be String, int, whatever.
  static class ForceClosedMessage extends Thread {
    public void run() {
      System.out.println(message);
    }
  }
  public static void main(String... args) {
    Runtime.getRuntime().addShutdownHook(newForceClosedMessage());
    //Go about your business
  }
}
1
On

You can use break() method in your while. For example:

int count = 1; 
while (count>0)
{
 count++;
 if(count==10){
      break();
 }
 }
 System.out.println(String.valueof(count));

This code finishes when count equals 10