在两个限制之间反弹值的最佳方法是什么?

时间:2014-05-05 14:40:18

标签: java

通过变量步骤递增然后递减两个限制之间的值的最佳方法是什么。例如:以" 0"开始,停在" 10",逐步" 1":0,1,2 ... 9,10,9, 8 ... 2,1,0,1,2 ......到目前为止(像yoyo)。

我的解决方案是:

public void something() {
    new Thread(new Runnable() {
        float counter = 0;
        int step = 5;

        @Override
        public void run() {
            while (true) {
                if (counter >= 100)
                    step = -5;
                if (counter <= 0)
                    step = 5;

                counter += step;
                // do something ...

                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                }
            }
        }
    }).start();
}

2 个答案:

答案 0 :(得分:1)

我建议将行为封装在自己的类中。类似的东西:

public class Yoyo {
  private final int from;
  private final int to;

  private int current;
  private int step;

  public Yoyo(int from, int to, int step) {
    if (step > to - from || to <= from) throw new IllegalArgumentException("invalid arguments");
    this.from = from;
    this.to = to;
    this.current = from - step;
    this.step = step;
  }

  public synchronized int next() {
    if (current + step > to || current + step < from) step = -step;
    return current += step;
  }

  public static void main(String[] args) {
    Yoyo y = new Yoyo(1, 10, 1);
    for (int i = 0; i < 25; i++) System.out.println(y.next());
  }
}

答案 1 :(得分:0)

您的答案似乎工作正常,但您也可以使用两个for循环:

for(int i=0;i<=10;i++) {
    counter = i;
    // Sleep here
}
for(int i=9;i>=0;i--) {
    counter = i;
    // Sleep here
}