gpt4 book ai didi

java - 如何使循环列表java中的输出随机

转载 作者:太空宇宙 更新时间:2023-11-04 09:54:53 27 4
gpt4 key购买 nike

这是一个鸭鸭鹅问题。输出应该是随机的。然而,我的输出和代码最终是[Scooby]。代码应该怎样写?

共有19个名字

http://collabedit.com/q248e

public class DuckDuckGoose {

public static void main(String[] args) {

LinkedList<String> linkedlist = new LinkedList<String>();
// add try catch to add list
try {
FileReader fr = new FileReader("C:\\Users\\src\\players.txt");
Scanner inFile = new Scanner(fr);
// while loop to get the next line with add to get the next name
while (inFile.hasNextLine()) {
linkedlist.add(inFile.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Iterator<String> iterator = linkedlist.iterator();
// to get the names of the list in loop
while(linkedlist.size() > 1){
while (iterator.hasNext()) {
iterator = linkedlist.iterator();
iterator.next();
// random number Goose landed method
if (getRandomBoolean()) {
iterator.remove();
}
if(linkedlist.size() == 1) break;
}
}

System.out.println(linkedlist);
}
// gets the random number with a different number .80
// than .5 that is half
public static boolean getRandomBoolean() {
return Math.random() < .80;
}

}

最佳答案


我尝试重用您的逻辑,以便您可以轻松理解。
现有代码中有 2 个错误,因此您每次都会得到相同的输出。

  1. 您每次在第二个 while 循环中都会重新初始化迭代器,因此您总是尝试删除第一个元素
  2. 如果没有删除,则需要将指针(迭代器)移动到下一个元素。或者每当 getRandomBoolean()false

    while(linkedlist.size() > 1){
    iterator = linkedlist.iterator(); // this is Point 1
    while (iterator.hasNext()) {
    iterator.next();
    // random number Goose landed method
    if (getRandomBoolean()) {
    iterator.remove();
    } else if (iterator.hasNext()) { // this is Point 2
    iterator.next();
    }
    if(linkedlist.size() == 1) break;
    }
    }

我测试过多次,效果很好。我希望能正确解释,如果您有更多问题,请告诉我。
谢谢

关于java - 如何使循环列表java中的输出随机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54282452/

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