mercredi 4 novembre 2015

Two random class returning same value

i tried to create random string contains both int and string. Below is the classes of how i get random string and int.

private int RandomNumber1(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }
    private int RandomNumber2(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }
    private string RandomStringSatu(int size, bool uppercase)
    {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();

        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (uppercase)
        return builder.ToString().ToUpper();
        return builder.ToString();
    }

    private string RandomStringDua(int size, bool uppercase)
    {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();

        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (uppercase)
            return builder.ToString().ToUpper();
        return builder.ToString();
    }

And here is the way i set up those classes to get a random string.

StringBuilder sb = new StringBuilder();
                sb.Append(RandomStringSatu(1, true));
                sb.Append(RandomNumber1(1, 9));
                sb.Append(RandomStringDua(1, true));
                sb.Append(RandomNumber2(1, 9));

                string rdmKode = sb.ToString();

this is the result that i get : Result

On the picture you can see that the first two caracters has same value with the last two caracter.

Now, the question is what should i do, if i want to get different caracter. So, the output should be looks like "D2B1"

Thanks




Aucun commentaire:

Enregistrer un commentaire