How to generate a random alpha-numeric string

前端 未结 30 2443
忘掉有多难
忘掉有多难 2020-11-21 05:38

I\'ve been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifie

30条回答
  •  走了就别回头了
    2020-11-21 06:04

    import java.util.Random;
    
    public class passGen{
        // Version 1.0
        private static final String dCase = "abcdefghijklmnopqrstuvwxyz";
        private static final String uCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        private static final String sChar = "!@#$%^&*";
        private static final String intChar = "0123456789";
        private static Random r = new Random();
        private static StringBuilder pass = new StringBuilder();
    
        public static void main (String[] args) {
            System.out.println ("Generating pass...");
            while (pass.length () != 16){
                int rPick = r.nextInt(4);
                if (rPick == 0){
                    int spot = r.nextInt(26);
                    pass.append(dCase.charAt(spot));
                } else if (rPick == 1) {
                    int spot = r.nextInt(26);
                    pass.append(uCase.charAt(spot));
                } else if (rPick == 2) {
                    int spot = r.nextInt(8);
                    pass.append(sChar.charAt(spot));
                } else {
                    int spot = r.nextInt(10);
                    pass.append(intChar.charAt(spot));
                }
            }
            System.out.println ("Generated Pass: " + pass.toString());
        }
    }
    

    This just adds the password into the string and... yeah, it works well. Check it out... It is very simple; I wrote it.

提交回复
热议问题