创建对象的增量计数器不起作用

时间:2015-03-17 21:36:11

标签: java

我只想增加一个变量numOfBodies,因为创建了一个新的Body并在我的主类中使用了这个值。为什么它不能正常工作?我虽然这是静态关键字的工作方式?

int deltaTime = 500*Body.getNum();

public class Body {
    public static int numOfBodies;

    public Body(){
        numOfBodies++;
    }

    public static int getNum(){
        return numOfBodies;
    }
}

1 个答案:

答案 0 :(得分:1)

基于此评论:

  

我认为这与问题无关。一旦我启动程序,按下'm',我当然会创建一个实体。我想要的是deltaTime更新,因为我按'm'更多次,即创建更多的身体

似乎我的猜测是正确的,你假设deltaTime会在创建一个新的Body时自动递增,而这不是Java的工作方式。为了实现这一点,您需要显式更新deltaTime。一种方法是使用观察者设计模式,可能使用PropertyChangeSupport在创建新Body时更新deltaTime。

虽然说过,我以前从未使用过PropertyChangeListener来监听静态属性。

但是例如:

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Scanner;

public class TestBody {
   private static final String QUIT = "quit";
   public static int deltaTime = 0;

   public static void main(String[] args) {
      Body.addPropertyChangeListener(Body.NUM_OF_BODIES,
            new PropertyChangeListener() {

               @Override
               public void propertyChange(PropertyChangeEvent evt) {
                  deltaTime = 500*Body.getNum();
                  System.out.println("deltaTime: " + deltaTime);
               }
            });

      Scanner scan = new Scanner(System.in);
      String line = "";
      while (!line.contains(QUIT)) {
         System.out.print("Please press enter to create a new body, or type \"quit\" to quit: ");
         line = scan.nextLine();
         Body body = new Body();
      }
   }
}

class Body {
   public static final String NUM_OF_BODIES = "num of bodies";
   private static PropertyChangeSupport pcSupport = new PropertyChangeSupport(
         Body.class);
   private static volatile int numOfBodies;

   public Body() {
      int oldValue = numOfBodies;
      numOfBodies++;
      int newValue = numOfBodies;
      pcSupport.firePropertyChange(NUM_OF_BODIES, oldValue, newValue);
   }

   public static int getNum() {
      return numOfBodies;
   }

   public static void addPropertyChangeListener(PropertyChangeListener l) {
      pcSupport.addPropertyChangeListener(l);
   }

   public static void removePropertyChangeListener(PropertyChangeListener l) {
      pcSupport.removePropertyChangeListener(l);
   }

   public static void addPropertyChangeListener(String propertyName,
         PropertyChangeListener l) {
      pcSupport.addPropertyChangeListener(propertyName, l);
   }

   public static void removePropertyChangeListener(String propertyName,
         PropertyChangeListener l) {
      pcSupport.removePropertyChangeListener(propertyName, l);
   }
}