按一定几率产生天气状况

public class WeatherUtil {
    /**
     * 2种天气情况.
     */
    private String[] weathers = { "sunny", "rain" };

    /**
     * 每种天气情况对应的几率
     */
    private int[] rates;

    /**
     * 数轴
     */
    private List<Integer> list = new ArrayList<Integer>();

    /**
     * 计算数轴上的点
     *
     * @param j
     * @return
     */
    private int getRandomRate(int j) {
        int rate = 0;
        for (int i = 0; i < j; i++) {
            rate = rate + rates[i];
        }
        return rate;
    }

    /**
     * 构造一个数轴,每个选项对应一个区间
     */
    private void init(int[] sysWeathersPercent) {
        this.rates = sysWeathersPercent;
        list.add(0);
        for (int i = 0; i < weathers.length; i++) {
            list.add(getRandomRate(i + 1));
        }
    }

    /**
     * 使用Math 的random 方法产生一个0--100 的随机数种子,判断其落在那个区间上.返回该区间对应的天气.
     *
     * @return
     */
    public String getChoice(int[] sysWeathersPercent) {
        init(sysWeathersPercent);
        String weather = "";
        int random = (int) (100 * Math.random());
        for (int i = 0; i < weathers.length; i++) {
            if (list.get(i) <= random && random < list.get(i + 1)) {
                weather = weathers[i];
                break;
            }
        }
        return weather;
    }
}

你可能感兴趣的:(J#)