+3 votes
2.4k views
in Programming by Expert (6.4k points)
want a random string generator function in java.

thanks for answer!
closed

2 Answers

+3 votes
by (510 points)
selected by
 
Best answer
The best solution to a problem is usually the easiest one.
class randomstring {
        public static String genString(int length) {
                String string = "";
                java.util.Random random = new java.util.Random();
                int r;
                char c;
                for (int i=0; i < length; i++) {
                        r = random.nextInt(51); //base 52 random (both cases)
                        r++;
                        if (r <= 26) r = r + 64;
                        else if (r > 26) r = r + 70;
                        c = (char) r;
                        string = string + c;
                }
                return string;
        }
 
        public static void main(String args[]) {
                System.out.println(genString(24));
        }
}
 
0
by Expert (6.4k points)
Thanks @john its working . and i have modified System.out.println(genString(24));
to System.out.println(genString(5)); Because i need only 5 digitizes random number.
:)
0
by Expert (5.9k points)
@John you are right this is the right way, for a random string generated by java function, I used the same logic which you have written here. Thanks for sharing the information.
–1 vote
by (670 points)

This Function will give random string every time

public boolean fncGenerateRandString(Keyword objKeyword){
java.util.Random r = new java.util.Random();
    int i = 1, n = 0;
    char c;
    String str="Z";
    for (int t = 0; t < 3; t++) {
        while (true) {
            i = r.nextInt(10);
            if (i > 5 && i < 10) {
                if (i == 9) {
                    i = 90;
                    n = 90;
                    break;
                }
                if (i != 90) {
                    n = i * 10 + r.nextInt(10);
                    while (n < 65) {
                        n = i * 10 + r.nextInt(10);
                    }
                }
                break;
            }
        }
        c=(char)n;
        str= str + String.valueOf(c);
    }
    while(true){
    i = r.nextInt(10000000);
    if(i>999999)
        break;
    }
    str=str+i;
    System.out.println( str);
Enjoy!
0
by (510 points)
This answer doesn't even make sense!

Not a Member yet?

Ask to Folks Login

My Account

Your feedback is highly appreciated