Getting the code to randomly choose one of x amount of choices
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开发者_JAVA百科 SDK that is like it.
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);
Use the random function to generate an integer. That integer can be an index to a list of your options.
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);
精彩评论