-1

我是一个完整的Java新手。我正在研究类和方法。我正在尝试创建一个类变量来存储随机数生成器的最小值。

它必须是变量,而不是方法中的变量。有任何想法吗?我想用Math.random()发电机。就像是:

int ranNum = Math.random();

这会给我一个随机数,但我如何以这种方式找到最小值(或最大值)?

4

5 回答 5

0

如果你只是想为你的班级保持状态,这可能是:

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;
    }


}

请注意,此类是单例的,应在应用程序范围内使用以生成随机值。

于 2013-01-27T13:56:23.840 回答
0

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);
    }
 }
于 2013-01-27T13:42:42.523 回答
0

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.

于 2013-01-27T13:45:47.040 回答
0

我假设你要求这个:

int min = 50;
int max = 100;
int ranNum = min+(int)(Math.random()*((max-min) + 1));

这将生成一个从 min 到 max(包括)的随机数

于 2013-01-27T13:40:38.310 回答
0

用这个:

import java.util.Random;
Random rand = new Random();
int i = rand.nextInt( 7 - 0 + 1 ); // where 7 is max and 0 is min
于 2013-01-27T13:41:35.830 回答