gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:01:41 25 4
gpt4 key购买 nike

按可变步长递增和递减两个限制之间的值的最佳方法是什么。例如:从“0”开始,到“10”停止,以“1”为步长:0, 1, 2 ... 9, 10, 9, 8 ... 2, 1, 0, 1, 2 .. .到目前为止(就像溜溜球一样)。

我的解决方案是:

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();
}

最佳答案

我建议将行为封装在它自己的类中。像这样的东西:

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());
}
}

关于java - 在两个限制之间反弹值的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23475220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com