String AlphaNumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder sb = new StringBuilder();
for(int i =0; i<8; i++)
{
int index = (int)(AlphaNumeric.length() * Math.random());
sb.append(AlphaNumeric.charAt(index));
}
String str = sb.toString();
1 Answer
As noted, the error is attempting to access some index that does not exist.
Given that String alphaNumeric has some length, it is possible to use the Random class to find a value within the range.
Random rnd = new Random();
StringBuilder sb = new StringBuilder();
final int len = alphaNumeric.length();
// generate 8 random characters, adding each random character
// to the collector
for (int i = 0; i < 8; ++i) {
// get a random value within the range, 0...N exclusive
int index = rnd.nextInt(len);
sb.append(alphaNumeric.charAt(index));
}
The use of the Random allows selecting a random value within a given range.
public int nextInt(int bound)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All bound possible int values are produced with (approximately) equal probability.
Math.random()will always return a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. So index should be between0andAlphaNumeric.length() -1. The issue must be some where else.