[英]How do I fix my random number while loop?
我需要做的是制作一個數字生成器,它在生成 10 時停止並顯示在達到 10 之前嘗試了多少次。 為此,我還必須僅使用 while 循環。 這是我現在的代碼:
public static int RandomOccurrence()
{
int randNumber = (int)(Math.random()*20 + 1);
int count = 0;
while(randNumber != 11){
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
這是函數調用:
int number = RandomOccurrence();
System.out.println("It took " +number +" tries before 10 was generated");
System.out.println();
System.out.println();
但是當我運行代碼時,它會無限地打印“生成的數字為 2”。
這是您的代碼的固定版本,主要涉及將獲取隨機數的行移動到while
循環中:
public static int RandomOccurrence()
{
int randNumber = 0;
int count = 0;
while(randNumber != 10){//I changed the 11 to 10 because you said you wanted to stop at 10
randNumber = (int)(Math.random()*20 + 1);//added
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
System.out.println(RandomOccurrence());
示例結果:
The number generated is 1
The number generated is 4
The number generated is 20
The number generated is 19
The number generated is 10
5
我真的更喜歡向用戶指出作業問題的答案,而不是給他們提供有效的代碼。 因為我們試圖“教人釣魚”。
原始代碼的問題在於它必須在while
循環中生成另一個隨機數。 最簡單的方法是復制並粘貼用於生成第一個函數調用的相同函數調用。
PS:您現在很快就會看到“有不止一種方法可以做到!”
每次執行 while 循環時,您都應該更新隨機數:所以 randNumber = (int)(Math.random()*20 + 1); 應該在循環內
public static int RandomOccurrence(){
int count = 0;
int randNumber = 0;
while(randNumber != 11){
randNumber = (int)(Math.random()*20 + 1);
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
public static void main(String...args){
int number = RandomOccurrence();
System.out.println("It took " +number +" tries before 10 was generated");
System.out.println();
System.out.println();
}
我希望我能幫上忙
這是一個 1-liner:
long count = IntStream.generate(() -> (int)(Math.random() * 20 + 1))
.takeWhile(i -> i != 11).count();
見現場演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.