我正在使用我創建的隨機方法,而不是 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 中的方法是靜態的這一事實有關,但我無法想象如何解決這個問題。任何幫助將不勝感激!
uj5u.com熱心網友回復:
Math.random()回傳范圍內的浮點數 (double) [0, 1)。當您將該 double 轉換為整數時,它每次都會被截斷為 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);
}
}
請注意要轉換為整數的運算式周圍的額外括號。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/379172.html
