Java 带有随机数生成器和循环的代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26085454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Code with random number generator and loop
提问by Julac Ontina
I use this random number generator and it works fine but then I needed a range (e.g. 16-20) of numbers but I can't get it to work. I have no idea what to do.
我使用这个随机数生成器,它工作正常,但后来我需要一个范围(例如 16-20)的数字,但我无法让它工作。我不知道该怎么做。
for (int i = 1; i <= 1; i++) {
int RandomAttack = (int) Math.random() * 20;
System.out.println(RandomAttack);
}
I need the simplest code there is.
我需要最简单的代码。
采纳答案by Adam
Math.random() will only return numbers in range 0..1. You could scale this by multipling by range and adding on minimum.
Math.random() 只会返回 0..1 范围内的数字。您可以通过乘以范围并添加最小值来扩展它。
Or use java.util.Random(), this has a handy method nextInt()which will return between 0 and < value.
或者使用 java.util.Random(),它有一个方便的方法nextInt(),它将返回 0 和 < 值之间。
So you need to go 0<= value < 5 to have values 0, 1, 2, 3, 4
所以你需要去 0<= value < 5 有值 0, 1, 2, 3, 4
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
Random random = new Random();
for (int i = 1; i <= 10; i++) {
int value = 16 + random.nextInt(5);
System.out.println(value);
}
}
}
回答by Juxhin
Make sure you have your Random imported and initialised, Random random = new Random();
确保您已导入并初始化 Random, Random random = new Random();
Follow:
跟随:
int randomNumber = random.nextInt(max - min) + min;
In your case
在你的情况下
int randomNumber = random.nextInt(20 - 16) + min;
That alone should get you your desired value within range. Don't forgot to import Java's Random class on top of your class.
仅此一项就可以让您在范围内获得所需的价值。不要忘记在类的顶部导入 Java 的 Random 类。
Also, I'm not quite understanding the point of your loop over there. Am I missing something obvious or is that just one iteration?
另外,我不太明白你在那里循环的重点。我错过了一些明显的东西还是只是一次迭代?
Here is a class example:
这是一个类示例:
import java.util.Random;
public class RandomRange {
private static Random random;
public static void main(String[] args) {
random = new Random();
System.out.println(random.nextInt(20 - 16) + 16);
}
}