除了一个元素外,我如何从数组列表中选择随机元素? 这是我的arraylist:
ArrayList <String> provinces = new ArrayList();
Collections.addAll(
provinces,
"New Brunswick",
"Saskatchewan",
"Ontario",
"Nova Scotia",
"Quebec",
"Alberta");
对于这个例子,我想随机选择其他元素,除了萨斯喀彻温省。
我尝试过:
for(int i == provinces.get (0); i < provinces.get(1); i > provinces.get(2); i < provinces.get(5)) {
int getPossibleAnswers = (int) Math.floor(Math.random()*i);
String displayPossibleAnswers = provinces.get(getPossibleAnswers);
outputAnswers.append(displayPossibleAnswers + "\n");
}
显然,这段代码不起作用,我不知道该怎么做。 提前致谢!
答案 0 :(得分:4)
构建所有索引值的列表,除了Saskatchewan的索引,然后将其洗牌。
List<String> provinces = Arrays.asList("New Brunswick", "Saskatchewan", "Ontario", "Nova Scotia", "Quebec", "Alberta");
List<Integer> indexes = new ArrayList<>();
for (int i = 0; i < provinces.size(); i++)
if (! provinces.get(i).equals("Saskatchewan"))
indexes.add(i);
Collections.shuffle(indexes);
StringBuilder outputAnswers = new StringBuilder();
for (int i : indexes)
outputAnswers.append(provinces.get(i) + "\n");
System.out.print(outputAnswers);
示例输出
Nova Scotia
Quebec
Ontario
Alberta
New Brunswick
答案 1 :(得分:1)
为简明扼要,作为mentioned只需创建list
而不Saskatchewan
ArrayList <String> provinces = new ArrayList<>(Arrays.asList("New Brunswick",
"Ontario", "Nova Scotia",
"Quebec", "Alberta"));
然后随机播放list
Collections.shuffle(provinces);
演示
ArrayList <String> provinces = new ArrayList<>(Arrays.asList("New Brunswick",
"Ontario", "Nova Scotia",
"Quebec", "Alberta"));
Collections.shuffle(provinces);
StringBuilder builder = new StringBuilder();
for (String s:provinces) {
builder.append(s+"\n");
}
System.out.println(builder);
输出:
Quebec
New Brunswick
Alberta
Ontario
Nova Scotia
答案 2 :(得分:0)
ArrayList <String> provinces = new ArrayList<>();
String removeValue = null;
Collections.addAll(
provinces,
"New Brunswick",
"Saskatchewan",
"Ontario",
"Nova Scotia",
"Quebec",
"Alberta");
for (Iterator<String> iterator = provinces.iterator(); iterator.hasNext(); ) {
String value = iterator.next();
if (value.equals("Saskatchewan")) {
removeValue = value;
iterator.remove();
}
}
Collections.shuffle(provinces);
for(String p: provinces){
System.out.println(p);
}
provinces.add(removeValue);
我使用了Iterator
,因为增强型for
循环不适用于remove()
但没有Iterator
,您也可以使用索引(数字)循环。
没有Iterator
:
for (int j = 0; j<provinces.size(); j++) {
if(provinces.get(j).equals("Saskatchewan")){
removeValue = provinces.get(j);
provinces.remove(provinces.get(j));
}
}
也可以不使用Collections.shuffle()
创建自己的方法。要做到这一点,请查看this question。
答案 3 :(得分:0)
如果您经常需要随机化(例如,对于随机测试),您可以添加Qala Datagen依赖项,然后获取这样的随机元素:
String e = sample(provinces);
虽然你仍然需要从集合中删除额外的元素。
免责声明:我是lib的作者。