Java Random event Distributor sample _java

Source: Internet
Author: User

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
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.