0

I have a string and I want to select random character from string.But I selected the character i choose won't be just one will select the entire string. I'm going to assign the ones I chose to different variables so chosen must be different.

From example like this but this code not working because same values ​​come.

String s = "Hello";
int index = random.nextInt(s.length());
char x = s.charAt(index); // l
char y = s.charAt(index); // o
char z = s.charAt(index); // H
char w = s.charAt(index); // e
char q = s.charAt(index) // l

I'm really tried this algorithms but I can't make it.I'm new to Java so maybe there is something in java that will work for me on this subject.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 3
    For starters, `random.nextInt(s.length())` generates a single integer. `index`'s value doesn't change after that, unless you do `index = random.nextInt(s.length());` again. – Federico klez Culloca May 24 '22 at 10:50
  • `int index = random.nextInt(s.length());` will only execute the `random.nextInt` method once and save that one result in `int index`. It will not re-execute the random call every time to use that variable. You have to do that yourself. You could just not save the index in a variable and instead have an inline-call like `s.charAt(random.nextInt(s.length()))` – OH GOD SPIDERS May 24 '22 at 10:52
  • 2
    By the way, if you don't want repetition you could 1) [shuffle the string](https://stackoverflow.com/questions/3316674/how-to-shuffle-characters-in-a-string-without-using-collections-shuffle) 2) take the first, second, third etc. character of the shuffled string and put each into a variable. – Federico klez Culloca May 24 '22 at 10:53

0 Answers0