【发布时间】:2016-10-26 15:38:33
【问题描述】:
我很难弄清楚如何让 Java 计算随机生成的数字列表中的零数量,直到它达到“-10”或“+10”。
如果有任何帮助,我将不胜感激,
谢谢。
我的代码:
import java.util.Random;
public class RandomWalk
{
public static void main(String[] args)
{
Random rand = new Random();
int position = 0;
int stepsTotal = 0;
int zeroesTotal = 0;
while (position !=10 && position != -10) {
if (rand.nextDouble() < 0.5) {
position--;
}
if (rand.nextDouble() < 0.5) {
position++;
}
else {
zeroesTotal++ ;
}
stepsTotal++;
System.out.print(" " + position);
}
System.out.println();
System.out.println("The final position is: " + position);
System.out.println("The number of steps taken is: " + stepsTotal);
System.out.println("There are " + zeroesTotal + " zeroes." );
}
}
示例输出:(我数了 4 个零,而不是 21 个。)(这算什么?)
0 0 0 0 1 1 2 3 4 4 4 3 3 4 3 4 3 4 4 5 5 4 4 5 6 6 6 6 5 5 6 7 8 7 7 7 6 6 6 6 7 7 7 7 8 8 8 9 8 9 9 8 7 8 9 9 9 10
最终位置是:10
采取的步数为:58
有 21 个零。 (错误在哪里)
【问题讨论】:
-
在我看来,您的代码与您的问题陈述没有任何相似之处:“我无法准确弄清楚如何让 Java 计算随机生成的列表中的零数量直到达到“-10”或“+10”的数字。请修改 - 您希望在输出中看到什么?
-
我期待看到“有 x 个零”。上面输出的零数量正确。
标签: java if-statement while-loop count whitespace