我是一个完整的Java新手。我正在研究类和方法。我正在尝试创建一个类变量来存储随机数生成器的最小值。
它必须是类变量,而不是方法中的变量。有任何想法吗?我想用Math.random()
发电机。就像是:
int ranNum = Math.random();
这会给我一个随机数,但我如何以这种方式找到最小值(或最大值)?
如果你只是想为你的班级保持状态,这可能是:
public class MyRandom {
private static final MyRandom INSTANCE = new MyRandom();
public static MyRandom getInstance(){
return INSTANCE;
}
private int low;
private int high;
private Random r = new Random();
private MyRandom(){
}
public int getHigh() {
return high;
}
public int getLow() {
return low;
}
public synchronized int getRandom(){
int next = r.nextInt();
if (next < low){
low = next;
}
if (next > high){
high = next;
}
return next;
}
}
请注意,此类是单例的,应在应用程序范围内使用以生成随机值。
The following will give you Random numbers from 0-100
and also will give you the smallest:
import java.util.Random;
public class AcademicController
{
private static int i,a=0,small=500;
public static void main(String[] args)
{
Random ran=new Random();
for(i=0;i<100;i++)//enter the range here
{
a=ran.nextInt(100);//gives you any number from 0-99
System.out.println(a);
if(a<small)//if given number is < than previous, make this number small
small=a;
}
System.out.println("small is :"+small);
}
}
You can make your own random methods based on it.
/**
* Returns a random real number between 0 and x. The number is always
* smaller than x.
*
* @param x The maximum range
* @return A random real number
*/
public static int random(int x){
return (int) (Math.floor(Math.random() * x));
}
/**
* Returns a random real number between x1 (inclusive) and x2 (exclusive).
*
* @param x1 The inclusive
* @param x2 The exclusive
* @return A random real number between x1 and x2
*/
public static int random_range(int x1, int x2){
return (int) (Math.floor(x1 + (Math.random() * (x2 - x1))));
}
Hope these simple methods helps you.
我假设你要求这个:
int min = 50;
int max = 100;
int ranNum = min+(int)(Math.random()*((max-min) + 1));
这将生成一个从 min 到 max(包括)的随机数
用这个:
import java.util.Random;
Random rand = new Random();
int i = rand.nextInt( 7 - 0 + 1 ); // where 7 is max and 0 is min