private char[] str="............"; protected final char[] mm = new char[] {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'}; public String getRndString(int number) { StringBuffer sb = new StringBuffer(); Random random = new Random(); while(true){ for (int i = 0; i < number; i++) { sb.append(mm[random.nextInt(mm.length)]); } if(!sb.toString().equals(new String(str)){ break; } } return sb.toString(); }
如果要此字符串还不能与给定的一个字符串数组(如str(n))中的各个字符串相同。 请自己修改正则表达式package com.gzh.framwork.utility.common.Util;import java.util.*; import java.security.SecureRandom; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException;/*随机字符串bean*/public class RandomStrg { private String randomstr; private boolean allchars=false; //欠缺是8位字符串 private Integer length=new Integer(8); private HashMap hmap; private ArrayList lower=null; private ArrayList upper=null; private char[] single=null; private int singlecount=0; private boolean singles=false; private String algorithm=null; private String provider=null; private boolean secure=false; private Random random=null; private SecureRandom secrandom=null; private static long seed=0; private final float getFloat() { if(random==null) return secrandom.nextFloat(); else return random.nextFloat(); } /** * generate the Random object that will be used for this random number * generator * */ public final void generateRandomObject() throws Exception { if(seed++>=Long.MAX_VALUE) { seed=0; } // check to see if the object is a SecureRandom object if(secure) { try { // get an instance of a SecureRandom object if(provider!=null) { // search for algorithm in package provider random=SecureRandom.getInstance(algorithm,provider); random.setSeed(seed); } else { random=SecureRandom.getInstance(algorithm); random.setSeed(seed); } } catch(NoSuchAlgorithmException ne) { throw new Exception(ne.getMessage()); } catch(NoSuchProviderException pe) { throw new Exception(pe.getMessage()); } } else { random=new Random(); random.setSeed(seed); } }
/** * generate the random string * */ private final void generaterandom() { if(allchars) for(int i=0;i<length.intValue();i++) randomstr=randomstr+new Character((char)((int)34+ ((int)(getFloat()*93)))).toString(); else if(singles) { // check if there are single chars to be included if(upper.size()==3) { // check for the number of ranges max 3 uppercase lowercase digits // build the random string for(int i=0;i<length.intValue();i++) { // you have four groups to choose a random number from, to make // the choice a little more random select a number out of 100 // get a random number even or odd if(((int)(getFloat()*100))%2==0) { // the number was even get another number even or odd if(((int)(getFloat()*100))%2==0) // choose a random char from the single char group randomstr=randomstr+randomSingle().toString(); else // get a random char from the first range randomstr=randomstr+ randomChar((Character)lower.get(2), (Character)upper.get(2)).toString(); } else { // the number was odd if(((int)(getFloat()*100))%2==0) // choose a random char from the second range randomstr=randomstr+ randomChar((Character)lower.get(1), (Character)upper.get(1)).toString(); else // choose a random char from the third range randomstr=randomstr+ randomChar((Character)lower.get(0), (Character)upper.get(0)).toString(); } } } else if(upper.size()==2) { // single chars are to be included choose a random char from // two different ranges // build the random char from single chars and two ranges for(int i=0;i<length.intValue();i++) { // select the single chars or a range to get each random char // from if(((int)(getFloat()*100))%2==0) { // get random char from the single chars randomstr=randomstr+randomSingle().toString(); } else if(((int)(getFloat()*100))%2==0) { // get the random char from the first range randomstr=randomstr+randomChar((Character)lower.get(1), (Character)upper.get(1)).toString(); } else { // get the random char from the second range randomstr=randomstr+randomChar((Character)lower.get(0), (Character)upper.get(0)).toString(); } } } else if(upper.size()==1) { // build the random string from single chars and one range for(int i=0;i<length.intValue();i++) { if(((int)getFloat()*100)%2==0) // get a random single char randomstr=randomstr+randomSingle().toString(); else // get a random char from the range randomstr=randomstr+randomChar((Character)lower.get(0), (Character)upper.get(0)).toString(); } } else { // build the rand string from single chars for(int i=0;i<length.intValue();i++) randomstr=randomstr+randomSingle().toString(); } } else { // no single chars are to be included in the random string if(upper.size()==3) { // build random strng from three ranges for(int i=0;i<length.intValue();i++) { if(((int)(getFloat()*100))%2==0) { // get random char from first range randomstr=randomstr+randomChar((Character)lower.get(2), (Character)upper.get(2)).toString(); } else if(((int)(getFloat()*100))%2==0) { // get random char form second range randomstr=randomstr+randomChar((Character)lower.get(1), (Character)upper.get(1)).toString(); } else { // get random char from third range randomstr=randomstr+randomChar((Character)lower.get(0), (Character)upper.get(0)).toString(); } } } else if(upper.size()==2) { // build random string from two ranges for(int i=0;i<length.intValue();i++) { if(((int)(getFloat()*100))%2==0) // get random char from first range randomstr=randomstr+randomChar((Character)lower.get(1), (Character)upper.get(1)).toString(); else // get random char from second range randomstr=randomstr+randomChar((Character)lower.get(0), (Character)upper.get(0)).toString(); } } else // build random string for(int i=0;i<length.intValue();i++) // get random char from only range randomstr=randomstr+randomChar((Character)lower.get(0), (Character)upper.get(0)).toString(); } }
/** * generate a random char from the single char list * * @returns - a randomly selscted character from the single char list * */ private final Character randomSingle() { return(new Character(single[(int)((getFloat()*singlecount)-1)])); } /** * generate a random character * * @param lower lower bound from which to get a random char * @param upper upper bound from which to get a random char * * @returns - a randomly generated character * */ private final Character randomChar(Character lower,Character upper) { int tempval; char low=lower.charValue(); char up=upper.charValue(); // get a random number in the range lowlow - lowup tempval=(int)((int)low+(getFloat()*((int)(up-low)))); // return the random char return(new Character((char)tempval)); } /** * get the randomly created string for use with the * <jsp:getProperty name=<i>"id"</i> property="randomstr"/> * * @return - randomly created string * */ public final String getRandom() { randomstr=new String(); generaterandom(); // generate the first random string if(hmap!=null) { while(hmap.containsKey(randomstr)) { // random string has already been created generate a different one generaterandom(); } hmap.put(randomstr,null); // add the new random string } return randomstr; } /** * set the ranges from which to choose the characters for the random string * * @param low set of lower ranges * @param up set of upper ranges * */ public final void setRanges(ArrayList low,ArrayList up) { lower=low; upper=up; } /** * set the hashmap that is used to check the uniqueness of random strings * * @param map hashmap whose keys are used to insure uniqueness of random strgs * */ public final void setHmap(HashMap map) { hmap=map; } /** * set the length of the random string * * @param value length of the random string * */ public final void setLength(String value) { length=new Integer(value); } /** * set the algorithm name * * @param value name of the algorithm to use for a SecureRandom object * */ public final void setAlgorithm(String value) { algorithm=value; secure=true; // a SecureRandom object is to be used } /** * set the provider name * * @param value name of the package to check for the algorithm * */ public final void setProvider(String value) { provider=value; } /** * set the allchars flag * * @param value boolean value of the allchars flag * */ public final void setAllchars(boolean value) { allchars=value; }
import java.util.TreeSet; import java.util.Random;public class RandomString { private int length; private TreeSet strTree = null; protected final char[] m = new char[] {'A','B','C','D','E','F','G', 'H','I','J','K','L','M','N', 'O','P','Q','R','S','T','U','V','W','X','Y','Z', 'a','b','c','d','e','f','g', 'h','i','j','k','l','m','n', 'o','p','q','r','s','t','u','v','w','x','y','z', '0','1','2','3','4','5','6','7','8','9'}; /** * Contructor * * @param length the length of string generated randomly */ public RandomString( String[] existedStr,int length ) { //building a tree in order to compare efficiently strTree = new TreeSet(); for( int i = 0; i < existedStr.length ; i ++ ) { strTree.add( existedStr[i] ); } this.length = length; } public void setLength( int length ) { this.length = length; } public String generateRandomStr() { StringBuffer sb = new StringBuffer(); Random random = new Random(); while ( true ) { for ( int i = 0; i < this.length; i ++ ) { sb.append( m[random.nextInt(m.length)] ); } if( !strTree.contains(sb.toString()) ){ break; } } return sb.toString(); } public static void main( String[] args ) { String[] str = { "a","ab","abc","b" }; RandomString strs = new RandomString( str,1 ); System.out.println( "Random String whose length is equals to 1 is :" + strs.generateRandomStr() ); strs.setLength( 2 ); System.out.println( "Random String whose length is equals to 2 is :" + strs.generateRandomStr() ); strs.setLength( 3 ); System.out.println( "Random String whose length is equals to 3 is :" + strs.generateRandomStr() ); } }输出: Random String whose length is equals to 1 is :T Random String whose length is equals to 2 is :r0 Random String whose length is equals to 3 is :r06
//已知一个整数数组,在已给范围内随机取一个与已知数组内任何一个数都不相同的整数
protected void randomlt(int low, int high, int num[], int sum) {
i = 1;
while (i == 1) {
number = (int) ( (Math.random()) * (high - low)) + 1;
i = 2;
for (j = 0; j < sum; j++) {
if (number == num[j]) {
i = 1;
}
}
}
}
protected final char[] mm = new char[] {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'}; public String getRndString(int number) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
while(true){
for (int i = 0; i < number; i++) {
sb.append(mm[random.nextInt(mm.length)]);
}
if(!sb.toString().equals(new String(str)){
break;
}
}
return sb.toString();
}
static char ch[];
public static String factory(int length){
if(length>62 || length<0){
return null;
}
initChar();
char[] result = new char[length];
int left = 0, right = 0, pos;
Random r = new Random();
for(int i=0; i<length; i++){
pos = r.nextInt(63);
if(ch[pos] != '$'){
result[i] = ch[pos];
ch[pos] = '$';
}else{
left = pos-1;
right = pos+1;
while(true){
if(left>=0){
if(ch[left] != '$'){
result[i] = ch[left];
ch[left] = '$';
break;
}else{
left--;
}
} if(right>=0){
if(ch[right] != '$'){
result[i] = ch[right];
ch[right] = '$';
break;
}else{
right--;
}
}
}
}
}
return new String(result);
}
private static void initChar() {
char ch[]={'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j',
'k','l','m','n','o','p','q','r','s','t',
'u','v','w','x','y','z',};
MyClass.ch = ch;
}
}
static char ch[];
public static String factory(int length){
if(length>62 || length<0){
return null;
}
initChar();
char[] result = new char[length];
int left = 0, right = 0, pos;
Random r = new Random();
for(int i=0; i<length; i++){
pos = r.nextInt(62);
if(ch[pos] != '$'){
result[i] = ch[pos];
ch[pos] = '$';
}else{
left = pos-1;
right = pos+1;
while(true){
if(left>=0){
if(ch[left] != '$'){
result[i] = ch[left];
ch[left] = '$';
break;
}else{
left--;
}
}
if(right<length){
if(ch[right] != '$'){
result[i] = ch[right];
ch[right] = '$';
break;
}else{
right++;
}
}
}
}
}
return new String(result);
}
private static void initChar() {
char ch[]={'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j',
'k','l','m','n','o','p','q','r','s','t',
'u','v','w','x','y','z',};
MyClass.ch = ch;
}
}
请自己修改正则表达式package com.gzh.framwork.utility.common.Util;import java.util.*;
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;/*随机字符串bean*/public class RandomStrg
{ private String randomstr; private boolean allchars=false; //欠缺是8位字符串
private Integer length=new Integer(8); private HashMap hmap; private ArrayList lower=null; private ArrayList upper=null; private char[] single=null; private int singlecount=0; private boolean singles=false; private String algorithm=null; private String provider=null; private boolean secure=false; private Random random=null; private SecureRandom secrandom=null; private static long seed=0; private final float getFloat()
{
if(random==null)
return secrandom.nextFloat();
else
return random.nextFloat();
} /**
* generate the Random object that will be used for this random number
* generator
*
*/
public final void generateRandomObject()
throws Exception
{ if(seed++>=Long.MAX_VALUE)
{
seed=0;
} // check to see if the object is a SecureRandom object
if(secure)
{
try
{
// get an instance of a SecureRandom object
if(provider!=null)
{ // search for algorithm in package provider
random=SecureRandom.getInstance(algorithm,provider);
random.setSeed(seed);
}
else
{
random=SecureRandom.getInstance(algorithm);
random.setSeed(seed);
}
}
catch(NoSuchAlgorithmException ne)
{
throw new Exception(ne.getMessage());
}
catch(NoSuchProviderException pe)
{
throw new Exception(pe.getMessage());
}
}
else
{
random=new Random();
random.setSeed(seed);
} }
/**
* generate the random string
*
*/
private final void generaterandom()
{ if(allchars)
for(int i=0;i<length.intValue();i++)
randomstr=randomstr+new Character((char)((int)34+
((int)(getFloat()*93)))).toString();
else if(singles)
{
// check if there are single chars to be included if(upper.size()==3)
{
// check for the number of ranges max 3 uppercase lowercase digits // build the random string
for(int i=0;i<length.intValue();i++)
{
// you have four groups to choose a random number from, to make
// the choice a little more random select a number out of 100 // get a random number even or odd
if(((int)(getFloat()*100))%2==0)
{ // the number was even get another number even or odd
if(((int)(getFloat()*100))%2==0) // choose a random char from the single char group
randomstr=randomstr+randomSingle().toString();
else // get a random char from the first range
randomstr=randomstr+
randomChar((Character)lower.get(2),
(Character)upper.get(2)).toString();
}
else
{
// the number was odd if(((int)(getFloat()*100))%2==0) // choose a random char from the second range
randomstr=randomstr+
randomChar((Character)lower.get(1),
(Character)upper.get(1)).toString();
else // choose a random char from the third range
randomstr=randomstr+
randomChar((Character)lower.get(0),
(Character)upper.get(0)).toString();
}
}
}
else if(upper.size()==2)
{
// single chars are to be included choose a random char from
// two different ranges // build the random char from single chars and two ranges
for(int i=0;i<length.intValue();i++)
{
// select the single chars or a range to get each random char
// from if(((int)(getFloat()*100))%2==0)
{ // get random char from the single chars
randomstr=randomstr+randomSingle().toString();
}
else if(((int)(getFloat()*100))%2==0)
{ // get the random char from the first range
randomstr=randomstr+randomChar((Character)lower.get(1),
(Character)upper.get(1)).toString();
}
else
{ // get the random char from the second range
randomstr=randomstr+randomChar((Character)lower.get(0),
(Character)upper.get(0)).toString();
}
}
}
else if(upper.size()==1)
{ // build the random string from single chars and one range
for(int i=0;i<length.intValue();i++)
{
if(((int)getFloat()*100)%2==0) // get a random single char
randomstr=randomstr+randomSingle().toString();
else // get a random char from the range
randomstr=randomstr+randomChar((Character)lower.get(0),
(Character)upper.get(0)).toString();
}
}
else
{
// build the rand string from single chars
for(int i=0;i<length.intValue();i++)
randomstr=randomstr+randomSingle().toString();
}
}
else
{ // no single chars are to be included in the random string
if(upper.size()==3)
{ // build random strng from three ranges
for(int i=0;i<length.intValue();i++)
{ if(((int)(getFloat()*100))%2==0)
{ // get random char from first range
randomstr=randomstr+randomChar((Character)lower.get(2),
(Character)upper.get(2)).toString();
}
else if(((int)(getFloat()*100))%2==0)
{ // get random char form second range
randomstr=randomstr+randomChar((Character)lower.get(1),
(Character)upper.get(1)).toString();
}
else
{ // get random char from third range
randomstr=randomstr+randomChar((Character)lower.get(0),
(Character)upper.get(0)).toString();
}
}
}
else if(upper.size()==2)
{ // build random string from two ranges
for(int i=0;i<length.intValue();i++)
{
if(((int)(getFloat()*100))%2==0) // get random char from first range
randomstr=randomstr+randomChar((Character)lower.get(1),
(Character)upper.get(1)).toString();
else // get random char from second range
randomstr=randomstr+randomChar((Character)lower.get(0),
(Character)upper.get(0)).toString();
}
}
else // build random string
for(int i=0;i<length.intValue();i++) // get random char from only range
randomstr=randomstr+randomChar((Character)lower.get(0),
(Character)upper.get(0)).toString();
}
}
* generate a random char from the single char list
*
* @returns - a randomly selscted character from the single char list
*
*/
private final Character randomSingle()
{ return(new Character(single[(int)((getFloat()*singlecount)-1)]));
} /**
* generate a random character
*
* @param lower lower bound from which to get a random char
* @param upper upper bound from which to get a random char
*
* @returns - a randomly generated character
*
*/
private final Character randomChar(Character lower,Character upper)
{
int tempval;
char low=lower.charValue();
char up=upper.charValue(); // get a random number in the range lowlow - lowup
tempval=(int)((int)low+(getFloat()*((int)(up-low)))); // return the random char
return(new Character((char)tempval));
} /**
* get the randomly created string for use with the
* <jsp:getProperty name=<i>"id"</i> property="randomstr"/>
*
* @return - randomly created string
*
*/
public final String getRandom()
{ randomstr=new String(); generaterandom(); // generate the first random string if(hmap!=null)
{ while(hmap.containsKey(randomstr))
{
// random string has already been created generate a different one
generaterandom();
} hmap.put(randomstr,null); // add the new random string
} return randomstr;
} /**
* set the ranges from which to choose the characters for the random string
*
* @param low set of lower ranges
* @param up set of upper ranges
*
*/
public final void setRanges(ArrayList low,ArrayList up)
{
lower=low;
upper=up;
} /**
* set the hashmap that is used to check the uniqueness of random strings
*
* @param map hashmap whose keys are used to insure uniqueness of random strgs
*
*/
public final void setHmap(HashMap map)
{
hmap=map;
} /**
* set the length of the random string
*
* @param value length of the random string
*
*/
public final void setLength(String value)
{
length=new Integer(value); } /**
* set the algorithm name
*
* @param value name of the algorithm to use for a SecureRandom object
*
*/
public final void setAlgorithm(String value)
{
algorithm=value;
secure=true; // a SecureRandom object is to be used
} /**
* set the provider name
*
* @param value name of the package to check for the algorithm
*
*/
public final void setProvider(String value)
{
provider=value;
} /**
* set the allchars flag
*
* @param value boolean value of the allchars flag
*
*/
public final void setAllchars(boolean value)
{
allchars=value;
}
import java.util.Random;public class RandomString
{
private int length;
private TreeSet strTree = null; protected final char[] m =
new char[] {'A','B','C','D','E','F','G',
'H','I','J','K','L','M','N',
'O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z',
'0','1','2','3','4','5','6','7','8','9'};
/**
* Contructor
*
* @param length the length of string generated randomly
*/
public RandomString( String[] existedStr,int length ) {
//building a tree in order to compare efficiently
strTree = new TreeSet();
for( int i = 0; i < existedStr.length ; i ++ ) {
strTree.add( existedStr[i] );
}
this.length = length;
} public void setLength( int length ) {
this.length = length;
} public String generateRandomStr() {
StringBuffer sb = new StringBuffer();
Random random = new Random();
while ( true )
{
for ( int i = 0; i < this.length; i ++ ) {
sb.append( m[random.nextInt(m.length)] );
}
if( !strTree.contains(sb.toString()) ){
break;
}
}
return sb.toString();
} public static void main( String[] args ) {
String[] str = { "a","ab","abc","b" };
RandomString strs = new RandomString( str,1 );
System.out.println( "Random String whose length is equals to 1 is :" +
strs.generateRandomStr() );
strs.setLength( 2 );
System.out.println( "Random String whose length is equals to 2 is :" +
strs.generateRandomStr() );
strs.setLength( 3 );
System.out.println( "Random String whose length is equals to 3 is :" +
strs.generateRandomStr() );
}
}输出:
Random String whose length is equals to 1 is :T
Random String whose length is equals to 2 is :r0
Random String whose length is equals to 3 is :r06