有没有一种方法可以随机化Java中两个整数之间的增量/减量?

时间:2020-02-20 18:41:19

标签: java random increment decrement

我正在学习Java,需要制作车辆模拟器。

车辆可以在垂直或水平方向上每转一圈。

b) move method increments or decrements either x or y coordinates by 1.

我不知道我未完成的代码是否有帮助,但这是:


package vehicleSimulator;

public class Vehicle {
    int h; // horizontal coordinate instead of x
    int v; // vertical coordinate instead of y
    boolean isAlive = true; 

    public Vehicle(int h, int v, boolean isAlive) {
        this.h = h;
        this.v = v;
        this.isAlive = isAlive;
    }

    public void moveVehicle() {
        if (isAlive == true) {
            // ++ or -- x or y
        }

    }

非常感谢任何帮助或指向可以提供帮助的网站的链接。

1 个答案:

答案 0 :(得分:1)

您可以获取随机整数值并执行mod运算,并相应地更新x / y。

示例可能是:

int random = ThreadLocalRandom.current().nextInt(11111, 99999);

if (random % 7 == 0) { 
    x++;
} else if (random % 6 == 2) {
    y--;
} // and so on...

对其他操作使用不同的mod值...