我正在尝试编写一个code
,根据随机机会将值更改为-1或+1。它基本上是一个穿过街区的人。他从6开始,如果他在1结束他赢了,但如果他在11结束他输了。最终输出看起来像这样:
Here we go again... time for a walk!
Walked 37 blocks, and
Landed at Home
Here we go again... time for a walk!
Walked 19 blocks, and
Landed in JAIL
Here we go again... time for a walk!
Walked 13 blocks, and
Landed in JAIL
Here we go again... time for a walk!
Walked 25 blocks, and
Landed in JAIL
我写了以下代码:
public class Drunk {
public int street;
public double move;
public int i;
public boolean jail;
public static void drunkWalk() {
do {
street = 6;
move = Math.random();
i++;
if (move > 0.5) {
street++;
} else {
street--;
}
} while (street != 1 && street != 11);
if ( street == 1) {
jail = false;
} else {
jail = true;
}
for (; ; ) { --- } //This is the problem. It treats it as a method.
//How can I fix this?
}
}
答案 0 :(得分:1)
有些想法如下:
public static void main(String args[])
{
Drunk drunk = new Drunk();
while (true)
{
DrunkResult result = drunk.drunkWalkToJail();
System.out.println("Walked " + result.getSteps() + " blocks, and Landed at " + (result.isInJail() ? "Jail":"Home"));
}
}
public DrunkResult drunkWalkToJail()
{
int street;
int stepCount = 0;
do
{
street = 6;
double move = Math.random();
stepCount++;
if (move > 0.5)
{
street++;
}
else
{
street--;
}
}
while (street != 1 && street != 11);
return new DrunkResult(street == 11, stepCount);
}
和
public class DrunkResult
{
boolean jail = false;
int stepCount = 0;
public DrunkResult(boolean jail, int stepCount)
{
this.jail = jail;
this.stepCount = stepCount;
}
public boolean isInJail()
{
return jail;
}
public int getSteps()
{
return stepCount;
}
}
你可以并行行走(一群醉酒的人)并独立处理结果。