Java Fundamentals 17-random numbers, regular expressions

Source: Internet
Author: User
Tags local time uuid

A random number

1.math.random

Returns a value with a positive sign that is double greater than or equal to 0.0 and less than 1.0 . does not contain 1.0. [0,1];

 Public Static void Main (string[] args) {    // generate pseudo-random number     System.out.println (Math.random ());}

The result of the operation is:

2.Random class

An instance of this class is used to generate a pseudo -random number stream.

Construction Method Summary
Random()
Creates a new random number generator.
Random(long seed)
longcreates a new random number generator with a single seed.

What is a pseudo-random number? Let's look at an example

The random numbers generated by R1 and R2 are the same! What is this for?

This is the true meaning of the pseudo -word, which is the same as the random number generated by the same seed.

Method Summary
protected  int next(int bits)
Generates the next pseudo-random number.
 boolean nextBoolean()
Returns the next pseudo-random number, which is a uniformly distributed value taken from the sequence of this random number generator boolean .
 void nextBytes(byte[] bytes)
Generates a random byte and places it in a user-supplied byte array.
 double nextDouble()
Returns the next pseudo-random number, which is a value that is 0.0 1.0 evenly distributed between and between this random number generator sequence. double
 float nextFloat()
Returns the next pseudo-random number, which is a value that is 0.0 1.0 evenly distributed between and between this random number generator sequence. float
 double nextGaussian()
Returns the next pseudo-random number, which is a Gaussian ("normal") distribution from the sequence of this random number generator, the average of which is double 0.0 the standard deviation 1.0 .
 int nextInt()
Returns the next pseudo-random number, which is a uniformly distributed value in the sequence of this random number generator int .
 int nextInt(int n)
Returns a pseudo-random number, which is a value that is evenly distributed between 0 (inclusive) and the specified value (not included) from this random number generator sequence. int
 long nextLong()
Returns the next pseudo-random number, which is a uniformly distributed value taken from the sequence of this random number generator long .
 void setSeed(long seed)
Use a single long seed to set the seed for this random number generator.

3.ThreadLocalRandom class

is Java7 new class, the subclass of the random class, in the case of multi-threaded concurrency compared to random can reduce the competition of multi-threaded resources, to ensure the problem of thread safety.

Threadlocalrandom is not instantiated directly with new, but is used for the first time with its static method, current ().

4.UUID class

Universal unique Recognition: A number generated on a machine that guarantees that all machines in the same time and space are unique.
* UUID is a 128-bit long number, generally expressed in 16 notation. The core idea of the algorithm is to combine the machine's network card, local time, a random number to generate the UUID.

Case: Generate Verification Code

ImportJava.util.Random;ImportJava.util.UUID; Public classYanzhengma { Public Static voidMain (string[] args) {//generate a 5-digit random number//intercept UUID to generate the first five bits of a stringString Num=uuid.randomuuid (). toString (). substring (0, 5); System.out.println (Num);//The second wayString str= "ABCDEFGHYJKLMNOPQISTUVWXYZ"; STR+=str.tolowercase (); STR+ = "0123456789";//stitching uppercase and lowercase letters and numbers togetherStringBuilder sb=NewStringBuilder (5);  for(inti=0;i<5;i++) {//Randomly take one character at a time in this spliced string        CharCh=str.charat (NewRandom (). Nextint (Str.length ()));//index must be between [0,str.lenth ()]//stitching with a StringBuildersb.append (CH); } System.out.println (SB);}}

Second, the regular expression

* Mainly used for (match judgment, split operation, replace operation), most of the match judgment

Take a look at a case:

Judge that a string is all made up of numbers

 Public classRegex { Public Static voidMain (string[] args) {String input= "1235sa65"; Booleanok=isnumber (input);    System.out.println (OK); }    //judge that a string is all made up of numbers    Private Static Booleanisnumber (String str) {Char[] arr=Str.tochararray ();  for(CharC:arr) {            if(c< ' 0 ' | | C> ' 9 ') {                return false; }        }        return true; }}

Is there some trouble?

Use regular Expressions below

 Public class Regex {    publicstaticvoid  main (string[] args) {        String input= " 1235sa65 ";        System.out.println ("123sa456". Matches ("\\d*"));}    }

The results of two are the same, with regular expressions simplifying the code and optimizing it.

Let's look at the methods in the Pattern class

Method Summary
static Pattern compile(String regex)
Compiles the given regular expression into the pattern.
static Pattern compile(String regex, int flags)
Compiles the given regular expression into the pattern with the given flag.
 int flags()
Returns the matching flag for this pattern.
 Matcher matcher(CharSequence input)
Creates a match for the given input with this pattern.
static boolean matches(String regex, CharSequence input)
Compiles the given regular expression and attempts to match the given input with it.
 String pattern()
Returns the regular expression in which this pattern has been compiled.
static String quote(String s)
Returns the specified literal String pattern String .
 String[] split(CharSequence input)
A match around this pattern splits the given input sequence.
 String[] split(CharSequence input, int limit)
A match around this pattern splits the given input sequence.
 String toString()
Returns a string representation of this pattern.

Common matches and split and ToString with a replace and a replaceall

A case to understand, judge the phone number

1: Requirement for one digit number

2: Section1bit is1, the first2bit is3,4,5,7,8one in the back .9bit is0to the9any number between the.

The result is: true

One more replacement case.

replace the numbers in the text with *


Java Fundamentals 17-random numbers, regular expressions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.