随机Classjava

Random Class java

我一直在做一些关于使用随机数的练习 class。

我有一个名为 Card 的 class,它有五个实例变量,其中包含对应位于指定范围内的整数的引用。

这五个数字是使用随机 class 生成的。代码如下:

public class Card
{

private String cardName;
private int yearOfInvention;
private int novelty;
private int popularity;
private double trendiness;
private int numberOfDialects;


public Card(String cardName) {
    this.cardName = cardName;
    Random rand = new Random(); 
    yearOfInvention = 1900 + rand.nextInt(111);
    novelty = rand.nextInt(10);
    popularity = rand.nextInt(100);
    trendiness = rand.nextDouble() + rand.nextInt(4);
    numberOfDialects = rand.nextInt(50);
 }

对于'trendiness',我的值需要是0-5之间的任意数字,包括小数部分,但只保留一位小数。

目前它会给我例如

私人双潮流1.2784547479963435

有没有办法限制小数点位数不四舍五入,影响'randomness'?

您可以使用如下格式的十进制数

double number = 0.9999999999999; // this is eg of double no
DecimalFormat numberFormat = new DecimalFormat("#.00"); // provide info about how many decimals u want 
System.out.println(numberFormat.format(number)); 
/**
 * return a float random number between max and it's negative
 */ 
public static float getFloatRandomNumber (int max){

    double isNegative = (Math.random()*10);

    //in case it's a negative number like 50:50
    if (isNegative<=5){
        float rand = (float)((Math.random() * max));
        return Float.parseFloat(String.format("%.3f", rand));
    }

    //in case it's positive number
    float rand = (float)(((Math.random() * max)) * -1); 
    return Float.parseFloat(String.format("%.3f", rand));    
}


/**
 * return an int random number between max and it's negative
 */
public static int getIntegerRandomNumberNoZero (int maximum){

    maximum = Math.abs(maximum);

    Random rn = new Random();
    double isNegative = (Math.random()*10);

    int rand = 0;
    int range = maximum + 1;

    //getting a random number which is not zero
    while(rand == 0){
        rand =  rn.nextInt(range);

        if (isNegative<=5){
            rand = Math.abs(rand);
        }
        else {
            rand = (Math.abs(rand) * -1);
        }               
    }           

    return rand;
}

最简单的方法可能是生成一个介于 0-50 之间的数字,然后除以 10。

trendiness = rand.nextInt(51) / 10d;

只是不要忘记添加描述性注释,或将其提取到具有适当名称的辅助方法中。这样的一行代码可能会让人感到困惑,因为它的意图不是很清楚。


编辑 回答 OP 的非常好的问题:

Why the digit between parentheses is 51 and not 50?

这由您决定哪个更正确。您的 "digit between 0-5" 规范不是很清楚。 rand.nextInt(51) 调用将在区间 [0, 50] 中生成一个随机整数。 rand.nextInt(50) 会在区间 [0, 50) 中生成一个数字(注意半开区间),即 0-49。你选择适合你的东西。

Also, what is the purpose of the d after the 10?

让我们看看。尝试 运行 这个:

System.out.println(new Random().nextInt(50) / 10);

它只输出数字0-4。问题是如果表达式中的所有数字都是整数,则除法是基于整数的。它将四舍五入任何小数余数。为避免这种情况,您需要在表达式中至少包含一个实数(通常是 double)。

这就是 10d 的作用。与 10.0(double)10.

相同