问题
I have been trying to reset a static variable that will keep count when certain methods are run. I want to be able to reset the counter after I return the output of one of the methods. The getEfficency will pull the value just fine, but after I run the getEfficency I would like for the static variable to be reset to 0, so that my program can run the other compute method.
public class Sequence {
private static int efficencyCount;
public static int computeIterative(int n) {
efficencyCount++;
}
public static int computeRecursive() {
efficencyCount++;
}
public static int getEfficiency() {
return efficencyCount;
}
}
回答1:
Just use a temp variable and set hour static to 0. Also you should keep protected your static variables to avoid misuse of your variables lutside of your class.
public static int getEfficiency (){
int temp=efficiencyCount;
efficiencyCount=0;
return temp;
}
回答2:
You can create a local variable and store the value of count temporarily. Reset the value of efficencyCount and return the value of local temporary count variable.
public static int getEfficiency() {
int count = efficencyCount;
efficencyCount = 0;
return count;
}
回答3:
You could do it as below:
Create a method
, and reset the efficencyCount
variable inside this method
public static void resetCounter() {
efficencyCount = 0;
}
回答4:
Create a temporary variable that holds the efficencyCount, then reset efficencyCount to zero.
public static int getEfficiency(){
int temp = efficencyCount;
efficencyCount = 0;
return temp;
}
来源:https://stackoverflow.com/questions/35446345/can-you-reset-a-static-variable