?????

public class Entry {

    public static void main(String[] args) {

        // 定义奖项数组,并为其设置值
        Awards[] awards = new Awards[4] ;
        awards[0] = new Awards("一等奖" , 1) ;
        awards[1] = new Awards("二等奖" , 2) ;
        awards[2] = new Awards("三等奖" , 3) ;
        awards[3] = new Awards("谢谢惠顾" , 4) ;

        // 补全代码
        Random r = new Random();
        for (int j = 0; j < 100; j++) {
            int i = r.nextInt(9);
            String name = binarySearch(awards, i).getName();
            System.out.println("恭喜您!" + name);
        }

    }

    // 二分查找实现
    public static Awards binarySearch(Awards[] awards , int num) {
        int leftIndex = 0;
        int totalWeight = 0;
        for (int i = 0; i < awards.length; i++) {
            int weight = awards[i].getWeight();
            totalWeight += weight;
        }
        int rightIndex = totalWeight - 1;
        while (leftIndex <= rightIndex){
            int midIndex = (leftIndex + rightIndex) / 2;
            if(midIndex > num){
                rightIndex = midIndex - 1;
            }else if (midIndex < num){
                leftIndex = midIndex + 1;
            }else {
                switch (num){
                    case 0:
                        return awards[0];
                    case 1:
                    case 2:
                        return awards[1];
                    case 3:
                    case 4:
                    case 5:
                        return awards[2];
                    case 6:
                    case 7:
                    case 8:
                    case 9:
                        return awards[3];
                }
            }
        }
        return null;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值