# Java随机百分比机会

go评论58阅读模式

Java Random Percentage Chance

# 问题

``````import java.util.Random;

public class Main {

public static void main(String[] args) {
int a = new Random().nextInt(10);
if (a >= 6) {
// 60% 的机会
System.out.println(a);
System.out.println("你获得了被动能力");
} else if (a >= 3) {
// 30% 的机会
System.out.println(a);
System.out.println("你获得了主动能力");
} else if (a >= 1) {
// 10% 的机会
System.out.println(a);
System.out.println("你获得了终极能力");
} else {
// 小于 10% 的机会（可能）
System.out.println(a);
System.out.println("你被赋予了所有能力。");
}
}
}
``````

Someone can u help me to show how to make a probability / chance with percentage ?

``````import java.util.Random;

public class Main {

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

Is my program correct ?

Ty

# 答案1

``````  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% 的概率
} else if (a < 9) {
// 30% 的概率
} else {
// 10% 的概率
}
``````

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

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

No, your program is not correct.

When you call `nextInt(10)`, you get a number in range 0 to 9, inclusive. You then segment that into the probability ranges you want, without reusing a number:

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

Which means the code should be:

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

Or you could go the other way:

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

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

• 本文由 发表于 2020年10月4日 17:37:32
• 转载请务必保留本文链接：https://go.coder-hub.com/64193070.html
• java
• percentage
• random

go 65

go 61

go 80

go 64