0

I want to count how often my recursive method is entered. The problem is that for every recursive call I use a different instance of that class. So my counter variable will always set back to origin value and then only count one time. So I get the same values no matter how often the method is entered.

One solution would be to create a new Class with a counter variable in it which would count it correctly. But is there a better solution? Looks not really nice.

static class SearchTree
{

      private Node node;
      private SearchTree left;
      private SearchTree right;

          private int count= 0;

This is my method where I want to use my count variable. It is always showing up 1 because I use it recursively with a new instance of SearchTree

 public SearchTree select(int i)
{

   if(node.size != 0)
      {
         count++;
     System.out.println("Count: " + count);
     left.select(i);               
}



private class Node
{
   public int key;
   public int size;

   public Node(int x, int size)
   {
      key = x;
      this.size= size;
   }

}

}
Optimal
  • 407
  • 3
  • 9

1 Answers1

3

count must be a class variable. You can declare a class variable by using the keyword static :

private static int count = 0;
Murat
  • 1,135
  • 8
  • 12