📄 randomnum.java
字号:
package com.singnet.util;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.util.Random;
public class RandomNum {
public Long randomnum = null;
public Float randomfloat = null;
public boolean floatvalue = false;
public long upper = 100;
public long lower = 0;
public String algorithm = null;
public String provider = null;
public boolean secure = false;
public Random random = null;
public SecureRandom secrandom = null;
public final float getFloat() {
if (random == null)
return secrandom.nextFloat();
else
return random.nextFloat();
}
public final void generateRandomObject() throws Exception {
// 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
secrandom = SecureRandom.getInstance(algorithm, provider);
else
secrandom = SecureRandom.getInstance(algorithm);
} catch (NoSuchAlgorithmException ne) {
throw new Exception(ne.getMessage());
} catch (NoSuchProviderException pe) {
throw new Exception(pe.getMessage());
}
} else
random = new Random();
}
/**
* generate the random number
*
*/
public final void generaterandom() {
int tmprandom = 0; // temp storage for random generated number
String rand;
// check to see if float value is expected
if (floatvalue)
randomfloat = new Float(getFloat());
else
randomnum = new Long(lower
+ (long) ((getFloat() * (upper - lower))));
}
public final Number getRandom() {
generaterandom();
if (floatvalue)
return randomfloat;
else
return randomnum;
}
public final void setRange(long low, long up) {
// set the upper and lower bound of the range
lower = low;
upper = up;
// check to see if a float value is expected
if ((lower == 0) && (upper == 1))
floatvalue = true;
}
/**
* 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
}
public final void setProvider(String value) {
provider = value;
}
public final void setRange(String value) throws Exception {
try {
upper = new Integer(value.substring(value.indexOf('-') + 1))
.longValue();
} catch (Exception ex) {
throw new Exception("upper attribute could not be"
+ " turned into an String default value was used");
}
try {
lower = new Integer(value.substring(0, value.indexOf('-')))
.longValue();
} catch (Exception ex) {
throw new Exception("lower attribute could not be"
+ " turned into an String default value was used");
}
if ((lower == 0) && (upper == 1))
floatvalue = true;
if (upper < lower)
throw new Exception("You can't have a range where the lowerbound"
+ " is higher than the upperbound.");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -