-2

The LinkedList only shows the same output. I am trying to use the last while loop but it does not work. This is a "Duck Duck Goose" problem. I am not supposed to use Indexing.

19 names

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(...players.txt");
        Scanner inFile = new Scanner(fr);

        while (inFile.hasNextLine()) {
            linkedlist.add(inFile.nextLine());
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Iterator<String> iterator = linkedlist.iterator();

    // checks until the last list
    while (!iterator.hasNext()) {
        if (iterator.next().equals(getRandomBoolean())) {
            iterator.remove();
        }
    }
    System.out.println(linkedlist);
}

public static boolean getRandomBoolean() {
    return Math.random() < 10 * 0.5;
}
}
ashkanaral
  • 19
  • 8

1 Answers1

0
if (iterator.next().equals(getRandomBoolean())) {

This is never true, because the iterator contains Strings, not Booleans, so you never execute the iterator.remove();.

Instead:

iterator.next(); // gets but ignores the next String.
if (getRandomBoolean()) {

Additionally, your loop never executes:

while (!iterator.hasNext()) {

because the iterator initially has a next element.

Remove the !.


Additionally, this:

Math.random() < 10 * 0.5

Is always true, because Math.random() is strictly less than 1, and 10 * 0.5 is 5.

Drop the 10 *, or pick a value on the RHS of the < which is between 0 and 1.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243