user3804738
user3804738

Reputation: 77

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

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

Upvotes: 6

Views: 62105

Answers (10)

Johnn Doee
Johnn Doee

Reputation: 1

This is a different version of how to increment a value to a file each time you run a program.

public class FileCount {
    int count=0;

    public int ScanForValue() throws IOException {
        if(! new File("C:\\Users\\name\\Desktop\\file.txt").exists())
            return 0;
        else{
            FileReader fr = new FileReader("C:\\Users\\name\\Desktop\\file.txt");
            Scanner scanFile = new Scanner(fr);
            String n =scanFile.nextLine();
            count = Integer.parseInt(n);
            scanFile.close();
        }
        return count;
    }

    public void increment() throws IOException {
        int newValue = ScanForValue();
        newValue++;
        System.out.println("counts: "+newValue);
        writeIntoFile(newValue);
    }

    public void writeIntoFile(int countNumber) throws IOException {
        FileWriter fw = new FileWriter("C:\\Users\\name\\Desktop\\file.txt");
        String fin = String.valueOf(countNumber);
        fw.write(fin);
        fw.close();
    }
}

Upvotes: 0

Ramesh Hiremath
Ramesh Hiremath

Reputation: 11

public class Arguments {

   private static int i = 1;

   //   Arguments() {
   //       System.out.println("Main method thread constructor incremented for "+ i++ + " time" +"\n");
   //   }

   public static void main(String[] args) {
        new Arguments().method();
        new Arguments().method();
        new Arguments().method();
        new Arguments().method();
        new Arguments().method();
        new Arguments().method();
   }

   private void method() {
       System.out.println("Main method value incremented for "+ i++ + " time" +"\n");
   }
}

Upvotes: 1

Suyash Saurabh
Suyash Saurabh

Reputation: 33

public static int count;

public int get(){
count=count+1;
return count;
}

Upvotes: 0

Oghli
Oghli

Reputation: 2340

you can declare static variable count

count will be part of the class, not part of any individual object.

now you only need to increment a count variable in each method call:

public class Test {
      // Set count to zero initially.
    static int count = 0;

    public static void main (String[] args) {

        Test test1 = new Test();

        test1.doMethod();

    }

    public void doMethod ()  {
        // Every time the method calls, increment count.
        count++;
        System.out.println(count);
    }
}

Update:

also you can instead of printing count inside doMethod () after each call

you can define static method as part of the class to get the value of the static variable count after method calls:

class Test
{   
    // Set count to zero initially.
    static int count = 0;

     public void doMethod ()  {
        // Every time the method calls, increment count.
        count++;
    }

    static int getCount(){
        // get latest value of count after method calls
        return count;
    }

    public static void main (String[] args) throws java.lang.Exception
        {
             Test test1 = new Test();

             test1.doMethod();

             test1.doMethod();

             test1.doMethod();

             System.out.println(Test.getCount());
        }
}

Upvotes: 0

gkbstar
gkbstar

Reputation: 635

As you want to know how many number of times your program has executed including current execution. So, for this either you need to write count to a file or you need to create a registry where you can put your counter and increase all the time your program execute through your program:

Following is an example of storing execution counter to a text file.

class Test {
    public static void main(String[] args) {

        Test test1 = new Test();

        test1.doMethod();

    }

    public int getCount() {

        int count = 0;
        try {
            if ( !new File("d:\\myCount.txt").exists())
                return 1;
            else {
                BufferedReader br = new BufferedReader(new FileReader(new File("d:\\myCount.txt")));
                String s = br.readLine();
                count = Integer.parseInt(s);
                br.close();
            }                
        } catch(Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    public void putCount(int count) {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(new File("d:\\myCount.txt")));
            bw.write(Integer.toString(count));
            bw.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void doMethod() { 
        int count = getCount();            
        System.out.println("You are running this program " + count + " number of times");
        count++;
        putCount(count);            
    }
}

Upvotes: 2

TheLostMind
TheLostMind

Reputation: 36304

declare int count = 0; either at instance level or at class level.

public void doMethod() {
    int count = 0; // a new count variable is created each time doMethod() is called
    count++;
    System.out.println(count);
}

Upvotes: 0

Simon
Simon

Reputation: 1416

If you declare the variable outside of a method, the state is remembered.

A solution could be:

public class Test {

    int count = 0;

    public static void main(String[] args) {
        Test test1 = new Test();
        test1.doMethod();
        test1.doMethod();
        test1.doMethod();
    }

    public void doMethod ()  {
        count++;
        System.out.println(count);
    }
}

This way count is created the moment you call new Test() and will be remembered until the Object is destroyed. Variables have something called a 'scope'. They can only be accessed in their scope and will only exist in that scope. Because you created count inside your void doMethod() method, it did not exist anywhere else. An easy way to look at the scope is by watching the brackets { } your variables are only stored inside those brackets. In my solution the brackets for count are the brackets for the entire Test class. Thus the variable is stored until the Object is destroyed.

More on scope: http://en.wikipedia.org/wiki/Scope_(computer_science)

I just noticed you mentioned you want the count value to remain after you run the program. You can do this by saving it in a database or file. However, you might have meant that you want the count value to remain after you run the void doMethod() method. I have edited my solution to execute the void doMethod() method three times so you see the value actually remains after running the method.

Upvotes: 0

Ashvini K
Ashvini K

Reputation: 55

Define your count variable out of that method:

public class Test {
    int count = 0;
    public static void main(String[] args) {
        Test test1 = new Test();

        test1.doMethod();

    }

    public void doMethod() {

        count++;
        System.out.println(count);
    }
}

Upvotes: 0

Jaithera
Jaithera

Reputation: 122

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.

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 121998

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().

Upvotes: 6

Related Questions