随机选择2个定义的数字

时间:2014-04-04 10:58:31

标签: java random

所以我有这段代码

if (x >= gameView.getWidth()) { //if gone of the right side of screen
    x = x - gameView.getWidth(); //Reset x
    y = random.nextInt(gameView.getHeight());
    xSpeed = 
    ySpeed = 
}

但我需要同时让xSpeedySpeed在两个值之间进行选择,“10”或“-10”,只有这两个数字,两者之间没有任何内容。

我看过的每个地方都说使用random.nextInt,但也可以从-10到10之间的数字中选择......

4 个答案:

答案 0 :(得分:6)

您可以尝试使用

xSpeed = (random.nextInt() % 2 == 0) ? 10 : -10;
ySpeed = (random.nextInt() % 2 == 0) ? 10 : -10;
祝你好运

答案 1 :(得分:3)

这个怎么样:

if(random.nextBoolean()){
     xSpeed = 10;
}
else xSpeed = -10;

答案 2 :(得分:2)

这个怎么样? Math.random()返回0.0(包含)和1.0(不包括)之间的值。

public class RandomTest {

    public static void main(String[] args) {
        int xSpeed = 0;
        int ySpeed = 0;

        if (Math.random() >= 0.5) {
            xSpeed = -10;
        } else {
            xSpeed = 10;
        }

        if (Math.random() >= 0.5) {
            ySpeed = -10;
        } else {
            ySpeed = 10;
        }
    }
}

答案 3 :(得分:2)

假设你的random.nextInt(gameView.getHeight());在偶数和奇数之间均匀分布,那么你可以这样写:

y = random.nextInt(gameView.getHeight()) % 2  == 0 ? 10 : -10;
相关问题