Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a variable increment on every running of a method?

Tags:

java

variables

I am trying to get the int count to increment each time I run the program. ie: So if I ran the program 9 times, and doMethod was called 9 times, the value of count would be 9. But since I have to initialize count to = 0 count keeps resetting itself to 0 on every iteration of the method. Is there a way around this?

public class Test {

    public static void main (String[] args) {

        Test test1 = new Test();

        test1.doMethod();

    }

    public void doMethod ()  {

        int count = 0;

        count++;
        System.out.println(count);
    }
}
like image 249
user3804738 Avatar asked Jan 11 '23 06:01

user3804738


2 Answers

Instead of making it as a local to method, make it as instance member.

int count = 0;
-----
public void doMethod() {
    count++;
    System.out.println(count);
}

So that it wont reset to 0 on each call of doMethod().

like image 129
Suresh Atta Avatar answered Jan 26 '23 23:01

Suresh Atta


If you want to increment count each time you run the program,

  • You have to store your counter variable count into a file or a database table
  • So every time when execution starts get value from storage-initialize to count -increment and print in method and store to storage after completion of method.
  • If you do so the variable count will be initialized to new value for each run of the program.
like image 32
Jaithera Avatar answered Jan 26 '23 23:01

Jaithera