user3439600
user3439600

Reputation: 149

Android/Java Loop Not Working Properly

I have 2 array lists

ArrayList<Character> answer = new ArrayList<Character>();
ArrayList<Button> buttons = new ArrayList<Button>();

Answer one contains a bunch of chars from the String correctA and the buttons has 20 buttons saved in to it. What i am trying to do is grab each letter from the answers array and assign each letter to an individual button.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    buttonStuff();

    //split string and add to array
    String correctA = "TestAnswer";
    for(char a : correctA.toCharArray()){
        answer.add(a);
    }
    Collections.shuffle(answer);

    Button btn;
    //in this case will loop 10 times as there are 10 characters in "testAnswer"
    for(int i = 0; i < answer.size(); i++){
        Random myRandomizer = new Random();
        btn = buttons.get(myRandomizer.nextInt(buttons.size()));
        char a = answer.get(myRandomizer.nextInt(answer.size()));
            btn.setText(String.valueOf(a));
    } 
}

I have tried a few different ways with random and everytime i run the app only 7 or 8 buttons are filled with a letter instead of the 10 that it should, what am i doing wrong?

Upvotes: 1

Views: 114

Answers (2)

Rory Stephenson
Rory Stephenson

Reputation: 379

You are overwriting your buttons as the random numbers are not unique. You should use something like this to get random but unique indexes for your buttons

ArrayList<Integer> indexes = new ArrayList<Integer>();
for(int i = 0; i < buttons.size(); i++) indexes.add(i);
Collections.shuffle(indexes);

You can use the indexes like so

for(int i = 0; i < answer.size(); i++){
    Random myRandomizer = new Random();
    btn = buttons.get(indexes.get(i));
    char a = answer.get(myRandomizer.nextInt(answer.size()));
        btn.setText(String.valueOf(a));
} 

Upvotes: 0

rgettman
rgettman

Reputation: 178263

You are choosing a random Button and a random char each time, but over the course of an entire loop, it is very likely that a Button is chosen twice, leaving another Button untouched.

You have already shuffled the letters in correctA, so they are already randomized. Just pick each button and each char in order.

for(int i = 0; i < answer.size(); i++){
    btn = buttons.get(i);
    char a = answer.get(i);
    btn.setText(String.valueOf(a));
} 

Upvotes: 2

Related Questions