JoshuaBrand
JoshuaBrand

Reputation: 177

Choose between 2 defined numbers randomly

So I have this piece of code

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 = 
}

but I need to get both xSpeed and ySpeed to choose between two values, either '10' or '-10' and only those two numbers, nothing in between.

Everywhere I've looked says use the random.nextInt but that also chooses from the numbers in between -10 and 10...

Upvotes: 1

Views: 8840

Answers (4)

Đrakenus
Đrakenus

Reputation: 540

How about this:

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

Upvotes: 3

Tarmo
Tarmo

Reputation: 4081

Lets suppose your random.nextInt(gameView.getHeight()); distributes evenly between even and odd numbers, then you could write something like this:

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

Upvotes: 2

Tanmay Patil
Tanmay Patil

Reputation: 7057

You may try using

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

Good luck

Upvotes: 6

Markus
Markus

Reputation: 1767

What about this? Math.random() returns values between 0.0 (include) and 1.0 (exclude).

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

Upvotes: 2

Related Questions