2013-11-28 18 views
0

我正在研究一個需要特定方法執行N次(在這種情況下,N = 5)的Java問題集。爲什麼這種方法和循環執行的次數比我想要的要多?

但是,由於某種原因,每次運行程序時,它都會執行(或至少打印出)10次。我無法弄清楚如何僅打印5次。

我對編程很陌生,所以很抱歉,如果這是一個簡單的修復。謝謝您的幫助!

public static void main (String [] args) 
{ 
    final int N = 5; 
    int sum = 0; 

    for (int i = 1; i <= N; i++) 
    { 
     drunkWalk(); 
     int stepCount = drunkWalk(); 
     sum += stepCount; 

     if (i == N) 
     { 
      System.out.println ("Average # of steps equals " + (sum/N)); 
     } 
    } 
}  


public static int drunkWalk() 
{ 

    int start = 5;      //initializes variables 
    int steps = 0; 
    int position = 0; 
    System.out.println ("Here we go again...time for a walk!"); 

    do 
    { 
     int direction = retInt(); 

     if (direction%2 == 0)    //Determines if it will go left, towards home/0 
     { 
     position = start - 1; 
     } 

     else       //Determines if it will go right, towards jail/10 
     { 
     position = start + 1; 
     } 

     start = position; 

     steps++; 
    } while (position != 0 && position != 10); 

    System.out.println ("Took " + steps + " steps, and"); 

    if (position == 0) 
    { 
     System.out.println ("Landed at HOME"); 
    } 

    else 
    { 
     System.out.println ("Landed in JAIL"); 
    } 

    System.out.println(); 

    return steps;        //So the sum of the # of steps can continue to be calculated for the sum in main's for loop 
} 

public static int retInt()      //Returns odd or even integer to determine the direction in drunkWalk() 
{ 
    return (int)(6 * Math.random()); 
} 

}

+1

嘗試調試程序。逐行執行,你會看到一切。 – alex

+0

您正在for循環中調用drunkwalk()2次。這是故意的嗎? – MultiplyByZer0

回答

4
drunkWalk(); 
int stepCount = drunkWalk(); 

你硬是把它叫做兩次。刪除第一個只走一次。請注意,它也不會分配它的返回值,所以它不會對返回的結果做任何事情。

+0

非常感謝你的回答!你是對的,那絕對有效。你如何分配返回值?那部分也一直讓我感到困惑。 – srsarkar7

+0

您已經在第二行指定了返回值:'int stepCount = drunkWalk();'。這裏'drunkWalk()'的結果被分配給變量'stepCount' –

相關問題