选举对象
1 package com.yeepay.sxf.xuanju; 2 /** 3 * 被选举对象 4 * @author sxf 5 * 6 * 7 */ 8 public class Channle { 9 //名字 10 private String name; 11 //比例 12 private Integer proportion; 13 14 public Channle() { 15 super(); 16 } 17 public Channle(String name, Integer proportion) { 18 super(); 19 this.name = name; 20 this.proportion = proportion; 21 } 22 public String getName() { 23 return name; 24 } 25 public void setName(String name) { 26 this.name = name; 27 } 28 public Integer getProportion() { 29 return proportion; 30 } 31 public void setProportion(Integer proportion) { 32 this.proportion = proportion; 33 } 34 35 36 37 }
选举流程
1 package com.yeepay.sxf.xuanju; 2 3 import java.util.HashSet; 4 import java.util.Random; 5 import java.util.Set; 6 /** 7 * 比例选举(存在缺陷,常常选举不到) 8 * @author sxf 9 * 10 */ 11 public class Proportion { 12 /** 13 * 比例选举 14 * A的比例50% 15 * B的比例30% 16 * C的比例20% 17 * @param args 18 */ 19 public static void main(String[] args) { 20 //获取选举对象 21 Set<Channle> set=getChannle(); 22 23 //算出当前随机数 24 Random random=new Random(System.currentTimeMillis()); 25 int a=random.nextInt(); 26 int b=Math.abs(a); 27 int c=b%100; 28 System.out.println("Proportion.main()"+c); 29 //进行选举 30 for (Channle channle : set) { 31 int d=channle.getProportion(); 32 //随机数小于等于比例 33 if(c<=d){ 34 System.out.println("Proportion.main()"+channle.getName()+"被选中"); 35 break; 36 } 37 } 38 39 40 41 } 42 /** 43 * 获取选举对象集合 44 * @return 45 */ 46 public static Set<Channle> getChannle(){ 47 Channle aChannle=new Channle("A", 50); 48 Channle bChannle=new Channle("B", 30); 49 Channle cChannle=new Channle("C",20); 50 Set<Channle> set=new HashSet<Channle>(); 51 set.add(aChannle); 52 set.add(bChannle); 53 set.add(cChannle); 54 return set; 55 } 56 }
时间: 2024-10-12 00:17:39