java的getRandomDouble()运用 请提供完整代码

  1. getRandomDouble()可以取得0-1之間的一個亂數,為double值,將其放大10倍以取得0-10之間的整數,但可能會丟出Exception。 題目:總共需取得10組整數。 限制:
    1. 每一組,呼叫getRandomDouble()取得數字如果發生Exception,則要重新取,最多只能試3次。也就是如果連續取3次都發生Exception,則印出「無法取得」。
    2. catch exception的block中,不能再寫try catch,例如
catch(IllegalStateException ex){
   try {} catch....
}

最後將取得的結果以及呼叫次數列印出來

例如:
 第1次取得 3 呼叫2次
 第2次取得 無法取得
 第3次取得 4 呼叫1次
 ..
 第10次取得 5 呼叫3次

//do not change
public static double getRandomDouble() throws IllegalStateException{
        double nextValue = ThreadLocalRandom.current().nextDouble();
        if ( (int)(nextValue*10) %2 == 1 ){
            throw new IllegalStateException("Something wrong, please try again!");
        }
        return nextValue;
}



import java.util.concurrent.ThreadLocalRandom;
public class RandomTest {
    public static int callCount = 0;
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            int result = getRandomInteger();
            System.out.println("第" + i + "次取得 " + (result != -1 ? result + " 呼叫" + callCount + "次" : "无法取得"));
        }
    }

    public static int getRandomInteger() {
        callCount = 1;
        int result = -1;

        while (callCount <= 3) {
            try {
                double randomDouble = getRandomDouble();
                result = (int) (randomDouble * 10);
                break;
            } catch (IllegalStateException e) {
                callCount++;
            }
        }

        return result;
    }

    public static double getRandomDouble() throws IllegalStateException {
        double nextValue = ThreadLocalRandom.current().nextDouble();
        if ((int) (nextValue * 10) % 2 == 1) {
            throw new IllegalStateException("Something wrong, please try again!");
        }
        return nextValue;
    }
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632