Java随机百分比机会

问题描述

有人可以帮助我展示如何用百分比来表示概率/机会吗?

import java.util.Random;

public class Main {

    public static void main(String[] args) {
        int a = new Random().nextInt(10);
        if (a >= 6) {
            // 60% chance
            System.out.println(a);
            System.out.println("You got a passive power");
        } else if (a >= 3) {
            // 30% chance
            System.out.println(a);
            System.out.println("You got an active power");
        } else if (a >= 1) {
            // 10% chance
            System.out.println(a);
            System.out.println("You got an ultimate power");
        } else {
            // <10% chance (maybe)
            System.out.println(a);
            System.out.println("You blessed with all powers.");
        }
    }
}

我的程序正确吗?

Ty

解决方法

否,您的程序不正确。

呼叫nextInt(10)时,您会得到一个介于0到9之间(包括0和9)的数字。然后,您可以将其细分为所需的概率范围,而无需重复使用数字:

  0  1  2  3  4  5  6  7  8  9
  └──────────────┘  └─────┘  ╵
    6 / 10 = 60%      30%   10%

这意味着代码应为:

int a = new Random().nextInt(10);
if (a < 6) {
    // 60% chance
} else if (a < 9) {
    // 30% chance
} else {
    // 10% chance
}

或者您可以采用其他方式:

//   0  1  2  3  4  5  6  7  8  9
//   ╵  └─────┘  └──────────────┘
//  10%   30%          60%

int a = new Random().nextInt(10);
if (a >= 4) {
    // 60% chance
} else if (a >= 1) {
    // 30% chance
} else {
    // 10% chance
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...