Java随机数的例子

该例子演示了随机数的产生,可通过设置最低数(minNum)和最高数(maxNum)以控制随机数的产生范围。
程序当前最低数固定为0,将从控制台上接收输入的数字作为最高数。
例子相对简单,仅供初学者参考。


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;


public class GRandom {

/**
* @author Jaenson
* @since 03/17/2011
*/
private int minNum=0;
private int maxNum=0;
private static InputStreamReader in;
private static BufferedReader reader;

public GRandom(){
in = new InputStreamReader(System.in);
reader = new BufferedReader(in);
}

public String GenerateRandomNum(int tarMinNum, int tarMaxNum){
String result="";
Random random = new Random();

/* Set Random Seed
Long longNum = System.currentTimeMillis();
random.setSeed(longNum);
*/

/* Boolean
String.valueOf(random.nextBoolean());
*/

/* Double
String.valueOf(random.nextDouble());
*/

/* Float
String.valueOf(random.nextFloat());
*/

/* Long
String.valueOf(random.nextLong());
*/

/* Gaussian Algorithm
String.valueOf(random.nextGaussian());
*/

/* Integer */
int n = tarMaxNum - tarMinNum + 1;
int i = random.nextInt(tarMaxNum) % n;
result = String.valueOf(tarMinNum + i);

return result;
}

public String readString() throws Exception{
String s = "";
char temp;
try{
s = reader.readLine();
}catch(IOException e){
System.out.println("Input error! Please restart the application.");
temp = (char) System.in.read();
System.exit(0);
}catch(Exception e){
System.out.println("Input error! Please restart the application.");
temp = (char) System.in.read();
System.exit(0);
}
return s;
}


public int printConsoleChar() throws IllegalArgumentException, Exception{
int random = 0;
char temp='a';
try{
minNum = 0;

System.out.print("Enter the number(Integer):");
maxNum = Integer.parseInt(readString());
/* Generate 100 times */
for(int i=0; i<100; i++){
random = Integer.parseInt(GenerateRandomNum(minNum, maxNum));
System.out.println("Random Number:"+random);
}
}catch(IOException e){
System.out.println("Input error! Please restart the application.");
temp = (char) System.in.read();
System.exit(0);
}catch(IllegalArgumentException e){
System.out.println("Illegal number! Please restart the application.");
temp = (char) System.in.read();
System.exit(0);
}catch(Exception e){
System.out.println("Input error! Please restart the application.");
temp = (char) System.in.read();
System.exit(0);
}
return random;
}

public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
GRandom GR= new GRandom();
GR.printConsoleChar();
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值