我有一個靜態變量totalcontainer
,我在main
方法分配值給它。 現在,當我把它在另一種方法中它給缺省值即0通過靜態變量的值給另一個函數
變量的值未在第二方法更新。
import java.util.ArrayList;
public class abc {
static int totalContainer;
static ArrayList<Integer> count = new ArrayList<Integer>();
public static void main(String args[]) {
count.add(2);
count.add(10);
count.add(15);
count.add(6);
count.add(8);
totalContainer = count.size();
System.out.println(totalContainer);
}
public static float getCpu() {
int getcontainer = totalContainer;
System.out.println("in get cpu " + getcontainer);
return getcontainer;
}
}
我打電話方法getCpu
從另一個類,並始終得到值爲0
我怎樣才能在其他類使用這個變量的值?
這是一個簡單的程序來演示我面臨的問題。
如何以及何時你叫'getCpu()'? 'abc'真的是你的應用程序的主要類? – Berger
也許這與你從不調用getCpu()'的事實有關? –
如果你從另一個類的'main'調用'getCpu()',那麼'main'可能還沒有在類'abc'中運行來設置'totalContainer'。 – khelwood