gpt4 book ai didi

java - 从ArrayList中获取随机文本

转载 作者:行者123 更新时间:2023-12-02 04:33:06 25 4
gpt4 key购买 nike

我刚刚学习 Java,在使用 ArrayList 或检索随机文本行时遇到问题。我想要实现的是在每次页面刷新时加载一个随机引用(来自列表)。以前从未做过数组/随机,不确定这是否是正确的方法?

到目前为止,这是有效的:https://jsfiddle.net/5wryh23L/

无效的代码:

 Random random = new Random(); 
int index = random.nextInt(10);


List<String> list = new ArrayList<String>();
list.add("quote1");
list.add("quote2");
list.add("quote3");
list.add("quote4");
list.add("quote5");

RandomExample obj = new RandomExample();
for(int i = 0; i < 10; i++){
System.out.println(obj.getRandomList(list));
}

}

getRandomList(List<String> list) {

//0-4
int index = random.nextInt(list.size());
System.out.println("\nIndex :" + index );
return list.get(index);

}

最佳答案

从列表中获取随机项目的非常简单的方法:

list.get((int)(Math.random()*list.size()));

关于java - 从ArrayList中获取随机文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31192261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com