2015-07-21 75 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(一羣醉酒的人)並獨立處理結果。