使用Static计算对象

时间:2014-02-15 04:28:51

标签: java static

我无法完成这项工作。我必须保持Driver1完全相同。我的StaticCounter类需要做什么?

public class Driver1
{
public static void main(String[] args)
   {
   for (int i=0; i<10; i++)
      {
         System.out.println("Counter returned: " +
         StaticCounter.count());
      }
   }
}

StaticCounter.java
public class StaticCounter
{
   public static int count()
   {
       static int id;
       id=count++;
    }
}

3 个答案:

答案 0 :(得分:1)

我想你可能正在寻找类似的东西:

public class StaticCounter{

    private static int count;

    public static int count(){
        return count++; //or ++count if you want to increment before getting value
    }

}

答案 1 :(得分:0)

public class StaticCounter{
    private static int count = 0;

    public static int count(){
        count = count+1;
        return count;
    }
}

答案 2 :(得分:0)

你的主要:

public class Driver1
{
public static void main(String[] args)
   {
   public StaticCounter static = new StaticCounter();
   for (int i=0; i<10; i++)
      {
         System.out.println("Counter returned: " + count(i));
      }
   }
}

和类StaticCounter

public class StaticCounter{

    private int count;

    public StaticCounter(){
        countt = 0;
    }

    public static int count(int i){
        count = i;
    }

}