我正在研究一個需要特定方法執行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());
}
}
嘗試調試程序。逐行執行,你會看到一切。 – alex
您正在for循環中調用drunkwalk()2次。這是故意的嗎? – MultiplyByZer0