2014-04-04 247 views
1

所以我有这样的一段代码选择随机

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之间......

回答

6

您可以尝试使用

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

好运

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; 
     } 
    } 
} 
2

让我们假设你的random.nextInt(gameView.getHeight());偶数和奇数之间分布均匀,然后你可以写这样的事情:

y = random.nextInt(gameView.getHeight()) % 2 == 0 ? 10 : -10; 
+0

random.nextInt(n)给出0和n之间的随机数。它绝不会在负数和正数之间平均分配。 –

+1

你是对的。我的错。编辑答案。 – Tarmo

3

这个怎么样:

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