Reputation: 43
I used to program with a language where, if I wanted a number from a set of different numbers, I could go x=choose(0,-1,2,5) and then it would randomly choose one of those options and give me a result. But since I've been working with Android and Java, I don't know a way to replicate that function as there's nothing I can find in the Android SDK that is like it.
Upvotes: 0
Views: 324
Reputation: 15623
Assume that your numbers are placed in an integer array:
int[] numbers = {0, -1, 2, 5};
You can put a random number into x as:
int x = numbers[Random.nextInt(4)];
EDIT:
Probably creating a static function in a class would make this solution more like the one you used with your previous language:
public class MyUtil{
private static Random random = new Random();
public static int choose(int ... numbers){
return numbers[random.nextInt(numbers.length)];
}
}
You can use this function anywhere in your code as:
int x = MyUtil.choose(0, -1, 2, 5);
Upvotes: 1
Reputation: 22446
You can use the varargs feature:
private static Random random = new Random();
public static int choose(int ... numbers){
return numbers[random.nextInt(numbers.length)];
}
This will make your code very similar to what you expect. The array creation is implicit:
int x = choose(1,5,20,4);
Upvotes: 0
Reputation: 48577
Use the random function to generate an integer. That integer can be an index to a list of your options.
Upvotes: 0