-4
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();
8
  • 4
    you are trying to access the 70th character of a String which is clearly less than 70 characters. Commented May 7, 2019 at 6:29
  • @san, You need to use AlphaNumeric.length() - 1 instead of AlphaNumeric.length() to generate the random values in your approach. Commented May 7, 2019 at 6:48
  • 1
    I don't think the exception is thrown in the code above. Commented May 7, 2019 at 6:53
  • 1
    If i dont miss something the given code should work fine and will never produce the given error as 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 between 0 and AlphaNumeric.length() -1. The issue must be some where else. Commented May 7, 2019 at 6:55
  • 2
    Possible duplicate of string index out of bound exception, String index out of range Commented May 7, 2019 at 7:03

1 Answer 1

2

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.

javadoc for Random:

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.

Example may be seen at this link

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.