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