Hi Guys,
I have a problem which in java i have a method called turn() is there a way to count the amount of times it gets called upon, ultimately counting the amount of turns?
Just create a static int variable outside the method, and increment inside the method.
Hi Guys,
I have a problem which in java i have a method called turn() is there a way to count the amount of times it gets called upon, ultimately counting the amount of turns?
initialize a counter variable with 0 in the method from which turn() is been invoked and increment this variable from method turn().
initialize a counter variable with 0 in the method from which turn() is been invoked and increment this variable from method turn().
This will work in some cases, but not if:
turn() is called from multiple methods, or
there are multiple instances of the class and the methods are not static.
Making the counter static outside any method avoids both problems.
Thanks guys for your fast response!
I am still new to java. Would you guys be able to provide me an example on how this is implemented? or even point me in the right direction?
This will work in some cases, but not if:
turn() is called from multiple methods, or
there are multiple instances of the class and the methods are not static.Making the counter static outside any method avoids both problems.
yes, i didn't thought about this.
well, this is an wonderful forum for people like me who are trying to learn java.
With all the java experts it becomes easier to learn.
Thanks
Would you guys be able to provide me an example on how this is implemented? or even point me in the right direction?
Somewhere in your class, but outside any method, declare an int variable with the static keyword - this means there is only one value for this variable which is shared between all the instances of the class.
In your turn() method just add 1 to the variable, so that will count how many times it's been called.
I can't say any more without just giving you the complete answer (cheating). This isn't hard stuff, just try and see how it goes.
In your turn() method just add 1 to the variable, so that will count how many times it's been called.
I can't say any more without just giving you the complete answer (cheating). This isn't hard stuff, just try and see how it goes.
Thanks a lot for your help! I have gotten it working :)
Thanks guys for your fast response!
I am still new to java. Would you guys be able to provide me an example on how this is implemented? or even point me in the right direction?
here is the code:
class xnn
{
int i=0;
public int turn()
{
i++;
return i;
}
}
class count
{
public static void main(String args[])
{
int count=0;
xnn obj1=new xnn();
count=obj1.turn();
count=obj1.turn();
count=obj1.turn();
System.out.println("turn() was invoked this many tims=" +count);
}
}
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.