Java 循环时如何修正随机数?
我需要做的是制作一个数字生成器,当它生成10时停止,并显示在达到10之前有多少次尝试。我还必须只使用while循环来实现这一点。下面是我的代码:Java 循环时如何修正随机数?,java,Java,我需要做的是制作一个数字生成器,当它生成10时停止,并显示在达到10之前有多少次尝试。我还必须只使用while循环来实现这一点。下面是我的代码: public static int RandomOccurrence() { int randNumber = (int)(Math.random()*20 + 1); int count = 0; while(randNumber != 11){ System.out.println("T
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”。这里是代码的固定版本,它主要涉及将获取随机数的行移动到
循环中,而循环:
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循环时,都应更新随机数:
所以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();
}
我希望我能提供帮助我真的更喜欢让用户找到家庭作业问题的答案,而不是给他们有效的代码。因为我们想“教人钓鱼”
原始代码的问题在于它必须在while
循环中生成另一个随机数。最简单的方法是复制并粘贴用于生成第一个函数调用的同一个函数调用
附言:你很快就会看到“有不止一种方法可以做到这一点!”这里有一个1-liner:
long count = IntStream.generate(() -> (int)(Math.random() * 20 + 1))
.takeWhile(i -> i != 11).count();
请参阅。再次查看您的while循环。在while循环退出之前需要做什么?你在while循环中没有做什么可以满足exit子句的要求呢?又是Tyler,你好。我想,这件事会带来巨大的好处……当你循环时,什么会导致randNumber
变成11?为什么你要循环到randNumber=11
?你要找的是10个,不是11个。@nomad,我只是想看看什么有效或无效。事后看来,这有点傻哈哈。