我正在处理一个 Java 问题集,该问题需要执行 N 次特定方法(在本例中,N = 5)。
但由于某种原因,每次我运行该程序时,它都会执行(或至少打印)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 ());
}
}
最佳答案
drunkWalk();
int stepCount = drunkWalk();
你实际上调用了两次。删除第一个,只走一次。请注意,它也不分配其返回值,因此它不会对返回的结果执行任何操作。
关于java - 为什么这个方法和 for 循环执行的次数比我想要的要多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20255620/