2

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.

Saturnian
  • 1,686
  • 6
  • 39
  • 65

2 Answers2

3

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
  }
}
David Fisher
  • 282
  • 2
  • 13
-2

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

  • He want to print the value before exiting the program on hitting Ctrl + C from command line (and not using the break statement). Anyway break is a statement not a method. Don't use brackets on break; – Md Shahbaz Ahmad Jul 19 '20 at 16:26