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;
}
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!