2015-07-21 70 views
-2

我正在尝试编写一个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

将方法内的循环移动。 – Keppil

+0

'for loop'在方法之外 – Rakesh

+0

@Rakesh谢谢:) – Saadat

回答

1

如何像somethink:

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; 

    } 

} 

你可以做平行散步lel(一群醉酒的人)并独立处理结果。