您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,java.util.Random
类可以用来生成随机数
java.util.Random
类:import java.util.Random;
Random
对象:Random random = new Random();
int[] array = {1, 4, 7, 9, 12};
int threshold = 3;
int count = 0;
for (int value : array) {
if (value > threshold) {
count++;
}
}
Random
对象的nextInt()
方法生成一个介于0(包括)和满足条件的元素数量(不包括)之间的随机数:int randomIndex = random.nextInt(count);
int selectedValue = array[randomIndex];
System.out.println("Selected value: " + selectedValue);
将以上代码整合到一个完整的示例中:
import java.util.Random;
public class ProbabilityTest {
public static void main(String[] args) {
int[] array = {1, 4, 7, 9, 12};
int threshold = 3;
int count = 0;
for (int value : array) {
if (value > threshold) {
count++;
}
}
Random random = new Random();
int randomIndex = random.nextInt(count);
int selectedValue = array[randomIndex];
System.out.println("Selected value: " + selectedValue);
}
}
这个示例将随机选择一个满足条件(值大于3)的元素。你可以根据需要修改数组和条件以进行不同的概率测试。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。