4 回答

TA貢獻1757條經驗 獲得超7個贊
您將要在靜態方法之外創建一個靜態變量:
private static int counter = 0;
調用該方法時,遞增變量:
public static void showObject(Object o){
System.out.println(counter + ": " + o);
counter++;
}

TA貢獻1851條經驗 獲得超4個贊
您可以使用靜態變量來計算方法被調用的次數。
public class Utilities {
private static int count;
public static void showObject (Object o) {
System.out.println(counter + ": " + o.toString());
count++;
}
// method to retrieve the count
public int getCount() {
return count;
}
}

TA貢獻1784條經驗 獲得超8個贊
將靜態計數器添加到您的班級:
public class Utilities {
// counter where you can store info
// how many times method was called
private static int showObjectCounter = 0;
public static void showObject (Object o) {
// your code
// increment counter (add "1" to current value")
showObjectCounter++;
}
}

TA貢獻2021條經驗 獲得超8個贊
您可以使用以下內容:
private static final AtomicInteger callCount = new AtomicInteger(0);
然后在你的方法中:
public static void showObject (Object o) { System.out.println(callCount.incrementAndGet() + ": " + o.toString()); }
使用AtomicInteger
使計數器線程安全。
添加回答
舉報