Java random string of utility classes

  • 2020-04-01 02:47:53
  • OfStack

One, the generation of Java random Numbers

In Java, there are three concepts of random Numbers, broadly speaking.
1. Get a long number of milliseconds of the current time by system.currenttimemillis ().
2. Returns a double value between 0 and 1 through math.random ().
3. Generate a Random number through the Random class, which is a professional Random tool class with powerful functions.

Ii. API description of Random class

1. Java API description
An instance of the Random class is used to generate a pseudo-random stream of Numbers. This class USES a 48-bit seed and is modified using a linear congruent formula (see Donald Knuth's The Art of Computer Programming, Volume 2, section 3.2.1).

If two Random instances are created from the same seed, the same sequence of method calls is made for each instance, and they generate and return the same sequence of Numbers. To ensure the implementation of the attribute, a specific algorithm is specified for the class Random.
Many applications will find the random method in the Math class easier to use.

2. Method summary
The Random ()
Create a new random number generator.

The Random (seed)
Create a new random number generator using a single long seed:
                Public Random(long seed) {setSeed(seed); The next method USES it to hold the state of the random number generator.

Protected int next (int bits)
Generate the next pseudo-random number.

Boolean nextBoolean ()
Returns the next pseudo-random number, which is a uniformly distributed Boolean value taken from the sequence of this random number generator.

Void nextBytes (byte [] bytes)
Generate random bytes and place them in a user-supplied array of bytes.

Double nextDouble ()
Returns the next pseudo-random number, which is the double value from the sequence of this random number generator, evenly distributed between 0.0 and 1.0.

Float nextFloat ()
Returns the next pseudorandom number, which is the evenly distributed float value between 0.0 and 1.0 from the sequence of this random number generator.

Double nextGaussian ()
Returns the next pseudorandom number, a gaussian (" normally ") double value taken from the sequence of this random number generator, with an average of 0.0 and a standard deviation of 1.0.

Int nextInt ()
Returns the next pseudo-random number, which is the evenly distributed int value in the sequence of this random number generator.

Int nextInt (int n)
Returns a pseudorandom number that is an int value taken from the sequence of this random number generator and distributed evenly between 0 (including) and the specified value (excluding).

Long nextLong ()
Returns the next pseudo-random number, which is a uniformly distributed long from the sequence of this random number generator.

Void setSeed (seed)
Set the seed of this random number generator with a single long seed.

Iii. Use instructions of Random class

1, with seeds and without seeds of the difference
The Random class essentially USES a policy to separate instances of Random with and without seeds.
In layman's terms, the difference is:
With seeds, each run produces the same result.
Without seeds, every run is generated randomly, there is no rule to speak of.
2. Create a Random object without seed
Random Random = new Random();
3. Create a Random object without seed
There are two ways:
1) Random Random = new Random(555L);
2) Random Random = new Random();
The random setSeed (555 l);

Comprehensive application

Here's how to use a recently written random number utility class:


   import java.util.Random;
    
   public class RandomUtils { 
   public static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
   public static final String letterChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
   public static final String numberChar = "0123456789";
    
   public static String generateString(int length) { 
   StringBuffer sb = new StringBuffer(); 
   Random random = new Random(); 
   for (int i = 0; i < length; i++) {
     sb.append(allChar.charAt(random.nextInt(allChar.length()))); 
   } 
   return sb.toString(); 
   } 
    
   public static String generateMixString(int length) { 
   StringBuffer sb = new StringBuffer(); 
   Random random = new Random(); 
   for (int i = 0; i < length; i++) {
   sb.append(allChar.charAt(random.nextInt(letterChar.length()))); 
   } 
   return sb.toString(); 
   } 
    
   public static String generateLowerString(int length) { 
   return generateMixString(length).toLowerCase(); 
   } 
    
   public static String generateUpperString(int length) { 
   return generateMixString(length).toUpperCase(); 
   } 
    
   public static String generateZeroString(int length) { 
   StringBuffer sb = new StringBuffer(); 
   for (int i = 0; i < length; i++) {
   sb.append('0'); 
   } 
   return sb.toString(); 
   } 
    
   public static String toFixdLengthString(long num, int fixdlenth) { 
   StringBuffer sb = new StringBuffer(); 
   String strNum = String.valueOf(num); 
   if (fixdlenth - strNum.length() >= 0) {
   sb.append(generateZeroString(fixdlenth - strNum.length())); 
   } else { 
     throw new RuntimeException( " The digital " + num + " That translates to length is zero " + fixdlenth + " An exception occurred to the string of! ");
   } 
   sb.append(strNum); 
   return sb.toString(); 
   } 
    
   public static String toFixdLengthString(int num, int fixdlenth) { 
   StringBuffer sb = new StringBuffer(); 
   String strNum = String.valueOf(num); 
   if (fixdlenth - strNum.length() >= 0) {
   sb.append(generateZeroString(fixdlenth - strNum.length())); 
   } else { 
   throw new RuntimeException( " The digital " + num + " That translates to length is zero " + fixdlenth + " An exception occurred to the string of! ");
   } 
   sb.append(strNum); 
   return sb.toString(); 
   } 
   public static void main(String[] args) { 
   System.out.println(generateString(15)); 
   System.out.println(generateMixString(15)); 
   System.out.println(generateLowerString(15)); 
   System.out.println(generateUpperString(15)); 
   System.out.println(generateZeroString(15)); 
   System.out.println(toFixdLengthString(123, 15)); 
   System.out.println(toFixdLengthString(123L, 15)); 
   } 
   } 

Operation results:
vWMBPiNbzfGCpHG
23 hyrahdjkkpwmv
tigowetbwkm1nde
BPZ1KNEJPHB115N
000000000000000
000000000000123
000000000000123
Process finished with exit code 0

Six, summarized

1. Random Numbers are commonly used. There are three generation methods in Java.
2. The Random class object is divided into whether it has seed or not. As long as the seed has the same seed, it will run for many times and generate Random Numbers in the same way.
3, with seed random number with seed object creation there are two ways, the effect is the same. But random Numbers with seeds don't seem very useful.
4. The function of Random covers the function of math.random ().
5, can do through the random number to achieve the random string and other complex random data.
Don't study random Numbers that don't repeat themselves.    

Supplementary code:


package com.test;
import java.util.Random;
public class RandomUtils {
 public static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
 public static final String LETTERCHAR = "abcdefghijkllmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
 public static final String NUMBERCHAR = "0123456789";

   
 public static String generateString(int length)
 {
  StringBuffer sb = new StringBuffer();
  Random random = new Random();
  for (int i = 0; i < length; i++) {
   sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
  }
  return sb.toString();
 }
  
    public static String generateMixString(int length)
    { 
            StringBuffer sb = new StringBuffer(); 
            Random random = new Random(); 
            for (int i = 0; i < length; i++)
            { 
                    sb.append(ALLCHAR.charAt(random.nextInt(LETTERCHAR.length()))); 
            } 
            return sb.toString(); 
    } 
     
    public static String generateLowerString(int length) { 
            return generateMixString(length).toLowerCase(); 
    } 
     
    public static String generateUpperString(int length) { 
            return generateMixString(length).toUpperCase(); 
    } 
     
    public static String generateZeroString(int length) { 
            StringBuffer sb = new StringBuffer(); 
            for (int i = 0; i < length; i++) { 
                    sb.append('0'); 
            } 
            return sb.toString(); 
    } 
     
    public static String toFixdLengthString(long num, int fixdlenth) { 
            StringBuffer sb = new StringBuffer(); 
            String strNum = String.valueOf(num); 
            if (fixdlenth - strNum.length() >= 0) { 
                    sb.append(generateZeroString(fixdlenth - strNum.length())); 
            } else { 
                    throw new RuntimeException(" The digital " + num + " That translates to length is zero " + fixdlenth + " An exception occurred to the string of! "); 
            } 
            sb.append(strNum); 
            return sb.toString(); 
    } 
     
    public static String toFixdLengthString(int num, int fixdlenth) { 
            StringBuffer sb = new StringBuffer(); 
            String strNum = String.valueOf(num); 
            if (fixdlenth - strNum.length() >= 0) { 
                    sb.append(generateZeroString(fixdlenth - strNum.length())); 
            } else { 
                    throw new RuntimeException(" The digital " + num + " That translates to length is zero " + fixdlenth + " An exception occurred to the string of! "); 
            } 
            sb.append(strNum); 
            return sb.toString(); 
    } 

    
    public static int getNotSimple(int[] param,int len)
    {
         Random rand = new Random();
         for (int i = param.length; i > 1; i--)
         {
             int index = rand.nextInt(i);
             int tmp = param[index];
             param[index] = param[i - 1];
             param[i - 1] = tmp;
         }
         int result = 0;
         for(int i = 0; i < len; i++)
         {
             result = result * 10 + param[i];
         }
         return result;
    }
    public static void main(String[] args) { 
            System.out.println(generateString(10)); 
            System.out.println(generateMixString(10)); 
            System.out.println(generateLowerString(10)); 
            System.out.println(generateUpperString(10)); 
            System.out.println(generateZeroString(10)); 
            System.out.println(toFixdLengthString(123, 10)); 
            System.out.println(toFixdLengthString(123L, 10)); 
            int[] in = {1,2,3,4,5,6,7};
            System.out.println(getNotSimple(in,3));
    } 
}


Related articles: