java - 如何在循环列表java中使输出随机
问题描述
这是一个鸭鸭鹅问题。输出应该是随机的。然而,我的输出和代码最后是 [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;
}
}
解决方案
我试图重用您的逻辑,以便您可以轻松理解。
现有代码中有 2 个错误,因此您每次都得到相同的输出。
- 您每次都在第二个 while 循环中重新初始化迭代器,因此您总是尝试删除第一个元素
然后,如果未删除,则需要将指针(迭代器)移动到下一个元素。或者无论
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; } }
我已经测试了多次它工作正常。我希望解释得当,如果您有更多问题,请告诉我。
谢谢
推荐阅读
- ios - 我无法在任何地方访问我的数组对象,如何快速访问它们?
- windows - Postgresql 不在启动 windows 10 上运行 psqrlc.conf 文件
- html - 如何通过接近 React 测试库中的另一个元素来获取元素
- html - 浮动旁边的 Flexbox - 为什么/如何占用剩余空间?
- php - 由于响应中出现空行而导致错误,同时使用 nusoap 创建 php webservice
- reactjs - 如何在 react-admin 资源中的 2 个列表组件之间共享实例
- typescript - 如何监控 TypeScript 的变化?
- reactjs - 类型 'Readonly<{}> & Readonly<{ children?: ReactNode; 上不存在属性 }>'。TS2339
- javafx - “java.lang.RuntimeException: java.lang.reflect.InvocationTargetException” - 无法确定错误来自何处
- c - select() 响应标准输入但不响应 /dev/tty