首页 > 解决方案 > 如何在循环列表java中使输出随机

问题描述

这是一个鸭鸭鹅问题。输出应该是随机的。然而,我的输出和代码最后是 [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;
    }

}

标签: java

解决方案



我试图重用您的逻辑,以便您可以轻松理解。
现有代码中有 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;
        }    
    }
    

我已经测试了多次它工作正常。我希望解释得当,如果您有更多问题,请告诉我。
谢谢


推荐阅读