mercredi 10 août 2016

For-loop only doing half the work I want it to, why?

While working on my android project I needed a bunch of random words, at first I generated words starting on a specific letter (a,b,c,...), Then I thought I would rather make a quick little helper that would make my work faster done, than manually type and sort them, so I open Eclipse and made this:

public static void main(String[] args) {

    words = new ArrayList();
    randomWords = new ArrayList();


    words.add("add");
    words.add("applied");
    words.add("deck");
    words.add("demonstrator");
    words.add("disability");
    words.add("dip");
    ...
    ... //Bunch of words
    ...
    words.add("kneel");
    words.add("knowledge");
    words.add("kid");


    //260 words in total

    System.out.println("word size " + words.size());



for (int i = 0; i < words.size(); i++) {


    Random random = new Random();
    int randomNumber = random.nextInt(words.size());

    String string = words.get(randomNumber);
    randomWords.add(string);
    System.out.println("words.add(\"" + string + "\");");
    words.remove(randomNumber); 

}

System.out.println("randomWord size " + randomWords.size());

'System.out.println("word size " + words.size());

^This line is giving me a number of 260.

System.out.println("randomWord size " + randomWords.size());

After running the for-loop I end up with 130 items added in randomWord ArrayList<> and other half still being in the words ArrayList<>


What did I miss and is wrong? Also, what exactly is happening in my code?

Any help is greatly appreciated!




Aucun commentaire:

Enregistrer un commentaire