开发者

add string every time when we executed program

开发者 https://www.devze.com 2023-02-03 04:34 出处:网络
how to add string in program when executed 1- first executed then add \"_X\" 2- second time executed than add \"_X_X\"

how to add string in program when executed 1- first executed then add "_X" 2- second time executed than add "_X_X" third time executed than add "_X开发者_JAVA百科_X_X" and so on


If you mean a method, you can do it like this:

public String appendSomething(String current){
    return current + "_X";
}


Hard to tell if you want to show if the application has been execute n times or if your running n instances of the same application in parallel.

Anyway, you'll have to use an external ressource (a file) to store the actual counter value.

If you want to show, how many times an application has been started, simply read the value from the file on every application start, increment the counter and write it back. Keep the incremented value in memory and assemble the display String.

If you want to show the nth running instance, again use the technique described above to get and store the actual value and decrement the value in that file just before an instance is being closed.

Note, that there are at least two problems with this approach, which may be a blocker in production code:

  1. The counter may not be decremented if the application terminates unexpected. You'll need exactly one exit point for your application and thus serious exception handling
  2. Concurrent modification of the file may result in wrong counters. If two instances are created at exactly the same time, they may both receive the same counter value. Irrelevant, if the instances are startet "by hand".


You can read about Serialization here.

http://www.javabeginner.com/uncategorized/java-serialization

I'm giving you only a hook, you must do your homework by yourself.


I don't exactly understand what you want to do. If you don't need to make it persistent then you could use a static variable in your class, like:

class TestClass {
  private static int count = 0;

  public void doExecute()
  {
    this.count++;
  }

  public static int getCount()
  {
    return count;
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消