为什么这个方法和循环执行的次数比我想要的多?

时间:2013-11-28 00:20:58

标签: java for-loop methods

我正在研究一个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 ());
}

}

1 个答案:

答案 0 :(得分:4)

drunkWalk();
int stepCount = drunkWalk();

你实际上称之为两次。删除第一个只走一次。请注意,它也没有分配其返回值,因此它不会对返回的结果执行任何操作。