这是鸭鹅问题。输出最终将是随机的。但是,我的输出和代码最后是[Scooby]。代码应该如何?
有19个名字
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;
}
}
答案 0 :(得分:0)
我试图重用您的逻辑,以便您可以轻松理解。
现有代码中有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;
}
}
我已经多次测试,一切正常。我希望它能正确解释,如果您还有其他问题,请告诉我。
谢谢