The following requirements:
20% probability to execute method A,
1% probability to execute method B,
29% probability to execute method C,
50% probability to execute the method D
If you use a sentence such as if random number to judge, it may be written in chaos, I wrote a random distributor, you can standardize the operation. The following code is used for this distributor:
Copy Code code as follows:
Create a Distributor
Randomdispatcher randomdispatcher = new Randomdispatcher ();
Set the probability of each event, note that the sum of probabilities is not necessarily 100 oh
Randomdispatcher.put (20, 1);
Randomdispatcher.put (1, 2);
Randomdispatcher.put (29, 3);
Randomdispatcher.put (50, 4);
Random
int retindex = Randomdispatcher.random ();
Perform different methods according to random results
Switch (retindex) {
Case 1:
System.out.println ("Do Method A");
Break
Case 2:
System.out.println ("Do Method B");
Break
Case 3:
System.out.println ("Do Method C");
Break
Case 4:
System.out.println ("Do Method D");
Break
Default
Break
}