0

I have made a string array with some names, now I want to change the order of the values and then use a for-loop. my only problem is that I don't know how to change the array values order. here is my code :

This is the array:

people = new ArrayList<>();

people.add("Sam");
people.add("John");
people.add("Kim");
people.add("Edison");

"text" is my textview and "people" is my array with 4 values. I have tried this:

int rando = (int)(Math.random() *4);
for (i=0; i< people.size(); i++) {
text.append(people.get(rando));
}

but it only prints one of the values four times. Like this:

KimKimKimKim

1
  • That's because rando never gets a different value other than the one it gets outside the loop. And even if it was set inside the loop (as it should), you will most likely get some duplicate value. Eventualy, all of them. Commented Feb 18, 2019 at 12:16

3 Answers 3

1

You can use Collections.shuffle(people); to get the shuffled names from the arraylist. One line code should do the trick you're looking for

textView.setText(TextUtil.join(",", Collections.shuffle(people));
Sign up to request clarification or add additional context in comments.

Comments

0

try this.This is how I shuffeled songs in my music player app

for (i=0; i< people.size(); i++) {
shuffleText(people.size())
}
private void shuffleText(int size) {
      int randomNumber = new Random().nextInt((size) + 1) + 1;
      text.append(people.get(randomNumber));
  }

Comments

0

You can try this method

public static String getRandom(String[] people) {
   int rnd = new Random().nextInt(people.length);
   return people[rnd];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.