随机方法总是在for循环中返回最小值?
Random method always returning minimum value in for-loop?
我正在使用我创建的随机方法,而不是 java.util.Random class。 class 称为“Randomizer”,这是其中的代码:
public class Randomizer{
public static int nextInt(){
return (int)Math.random() * 10 + 1;
}
public static int nextInt(int min, int max){
return (int)Math.random() * (max - min + 1) + min;
}
}
这段代码应该可以正常工作,但是当我在 for 循环中调用它时(如下所示),它总是 returns 最小值。
public class Main
{
public static void main(String[] args)
{
System.out.println("Results of Randomizer.nextInt()");
for (int i = 0; i < 10; i++)
{
System.out.println(Randomizer.nextInt());
}
int min = 5;
int max = 10;
System.out.println("\nResults of Randomizer.nextInt(5, 10)");
for (int i = 0; i < 10; i++)
{
System.out.println(Randomizer.nextInt(min, max));
}
}
}
此代码returns以下:
Results of Randomizer.nextInt()
1
1
1
1
1
1
1
1
1
1
Results of Randomizer.nextInt(5, 10)
5
5
5
5
5
5
5
5
5
5
我认为这个错误与 Randomizer 中的方法是静态的这一事实有关,但我无法想象我该如何解决这个问题。任何帮助将不胜感激!
Math.random()
returns [0, 1)
范围内的浮点数(双精度)。当您将该双精度值转换为整数时,它每次都会截断为 0。
要解决您的问题,您需要在尝试完成所有数学运算后进行转换。所以,它应该是这样的:
public class Randomizer{
public static int nextInt(){
return (int)(Math.random() * 10 + 1);
}
public static int nextInt(int min, int max){
return (int)(Math.random() * (max - min + 1) + min);
}
}
请注意要转换为整数的表达式周围的额外括号。
我正在使用我创建的随机方法,而不是 java.util.Random class。 class 称为“Randomizer”,这是其中的代码:
public class Randomizer{
public static int nextInt(){
return (int)Math.random() * 10 + 1;
}
public static int nextInt(int min, int max){
return (int)Math.random() * (max - min + 1) + min;
}
}
这段代码应该可以正常工作,但是当我在 for 循环中调用它时(如下所示),它总是 returns 最小值。
public class Main
{
public static void main(String[] args)
{
System.out.println("Results of Randomizer.nextInt()");
for (int i = 0; i < 10; i++)
{
System.out.println(Randomizer.nextInt());
}
int min = 5;
int max = 10;
System.out.println("\nResults of Randomizer.nextInt(5, 10)");
for (int i = 0; i < 10; i++)
{
System.out.println(Randomizer.nextInt(min, max));
}
}
}
此代码returns以下:
Results of Randomizer.nextInt()
1
1
1
1
1
1
1
1
1
1
Results of Randomizer.nextInt(5, 10)
5
5
5
5
5
5
5
5
5
5
我认为这个错误与 Randomizer 中的方法是静态的这一事实有关,但我无法想象我该如何解决这个问题。任何帮助将不胜感激!
Math.random()
returns [0, 1)
范围内的浮点数(双精度)。当您将该双精度值转换为整数时,它每次都会截断为 0。
要解决您的问题,您需要在尝试完成所有数学运算后进行转换。所以,它应该是这样的:
public class Randomizer{
public static int nextInt(){
return (int)(Math.random() * 10 + 1);
}
public static int nextInt(int min, int max){
return (int)(Math.random() * (max - min + 1) + min);
}
}
请注意要转换为整数的表达式周围的额外括号。