简体   繁体   中英

Why is this method and for loop executing more times than I want it to?

I'm working on a Java problem set that requires a particular method to be executed N number of times (in this case, N = 5).

For some reason, though, every time I run the program, it executes (or at least, prints out) 10 times. I cannot figure out how to make it print out only 5 times.

I'm very new to programming, so apologies if this is a simple fix. Thanks for the help!

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();

You literally call it twice. Remove the first one to walk just once. Note that it doesn't assign its return value either, so it wouldn't do anything with the result that's being returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM