【发布时间】:2022-01-15 06:51:41
【问题描述】:
我正在使用我创建的随机方法,而不是 java.util.Random 类。该类称为“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 循环中调用它时(如下所示),它总是返回最小值。
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));
}
}
}
此代码返回以下内容:
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 中的方法是静态的这一事实有关,但我无法想象如何解决这个问题。任何帮助将不胜感激!
【问题讨论】: