随机正整数生成类的JAVA实现
来源:互联网 发布:nginx引入端口 编辑:程序博客网 时间:2024/04/28 14:04
随机正整数生成类
/**
*Name:CreateRandomNumber.java
*Author:Richard
*Date:Apr-10,2006
*Version:1.0.0.0
*============================
*随机整数生成类
*============================
*Author Version Date Changes
*Richard 1.0.0.2 Apr-11,2006 use EXCEPTION to instead of "if"
*/
public class CreateRandomNumber{
protected int r_min;
protected int r_max;
protected int r_num;
protected int r_arr[];
protected int r_mid;
/**
*construct method
*/
public CreateRandomNumber(){
r_min = 0;
r_max = 0;
r_num = 0;
r_arr = new int[r_num];
r_mid = 0;
}
/**
*set method
*/
public CreateRandomNumber(int pr_min, int pr_max, int pr_num, int pr_mid){
try{
if(pr_num<0)
throw new CreateRandomArrayException("ERROR: Num is less than zero!");
else if(pr_min>pr_max)
throw new CreateRandomArrayException("ERROR: min is greater than max!");
else if(pr_mid<pr_min || pr_mid>pr_max)
throw new CreateRandomArrayException("ERROR: mid is not between min and max!");
else{
r_min = pr_min;
r_max = pr_max;
r_num = pr_num;
r_mid = pr_mid;
r_arr = new int[r_num];
}
}
catch(CreateRandomArrayException e){
System.out.println(e.getMessage());
}
}
/**
*create numbers between r_min and r_max as r_num setting
*/
public void createRandom(){
for(int i=0; i<r_num; i++){
int t = r_max-r_min;
r_arr[i] = r_min+(int)(t*Math.random());
}
}
/**
*print numbers
*/
public void printArr(){
System.out.println("===========The result===========");
for(int i=0; i<r_num; i++)
System.out.println("arr[" +i+ "]=" +r_arr[i]);
}
/**
*print the max and min result
*/
public void maxAndMin(){
int max = r_arr[0];
int min = r_arr[0];
for(int i=1; i<r_num; i++){
if(r_arr[i]>max)
max = r_arr[i];
if(r_arr[i]<min)
min = r_arr[i];
}
System.out.println("The max is :" +max);
System.out.println("The min is :" +min);
}
/**
*count how many numbers are greater than r_mid
*/
public int countNum(){
int count = 0;
for(int i=0; i<r_num; i++)
if(r_arr[i]>r_mid) count++;
return count;
}
/**
*count how many numbers are greater than pr_mid
*/
public int countNumEqualsrPr_mid(int pr_mid){
int count = 0;
for(int i=0; i<r_num; i++)
if(r_arr[i]==pr_mid) count++;
return count;
}
/**
*sort the r_arr[]
*/
public void sortArr(boolean isUpSort){
for(int i=0; i<r_num; i++){
for(int j=i; j<r_num; j++){
if(r_arr[j]<r_arr[i]){
int temp = r_arr[i];
r_arr[i] = r_arr[j];
r_arr[j] = temp;
}
}
}
if(!isUpSort){
for(int i=0; i<(int)(r_num/2+0.5); i++){
int temp = r_arr[i];
r_arr[i] = r_arr[r_num-1-i];
r_arr[r_num-1-i] = temp;
}
}
}
};
//==========End Class CreateRandomNumber==========
/**
*Class Name:CreateRandomArrayException
*=====================================
*use this class to process the exception in create random array
*/
class CreateRandomArrayException extends Exception{
/**
*construct method
*/
public CreateRandomArrayException(String msg){
super(msg);
}
};
//==========End Class CreateRandomArrayException==========