简体   繁体   中英

Beginner here and I'm having nested while loops issues

So we have part of an assignment with two parts. Here's what that part says.

A drunkard begins walking aimlessly, starting at a lamp post. At each time step, the drunkard forgets where he or she is, and takes one step at random, either north, east, south, or west, with probability 25%. How far will the drunkard be from the lamp post after N steps?

Write a program RandomWalker.java that takes an integer command-line argument N and simulates the motion of a random walker for N steps. After each step, print the location of the random walker, treating the lamp post as the origin (0, 0). Also, print the square of the final distance from the origin.

This program works properly, here's my code for it.

package project2;

import java.util.*;
import java.math.*;

public class RandomWalker {
    public static void main(String args[]){

        Scanner scan = new Scanner(System.in);
        Random rand = new Random();
        System.out.println("Enter the number of steps you want to take please.");
        int steps = scan.nextInt();
        int x = 0;
        int y = 0;
        int XorY;
        int dist;
        int count =0;
        while(count<steps){
            XorY = rand.nextInt(2);
            dist = rand.nextInt(2);
            if(XorY==0){
                if(dist==0)
                    dist = -1;
                x += dist;
                System.out.println("("+x+", " +y+")");
            }
            else{
                if(dist==0)
                    dist = -1;
                y += dist;
                System.out.println("("+x+", " +y+")");
            }
            count ++;
        }
        System.out.println("Squared Distance = " + (x*x + y*y));
    }
}

The second part is where I'm having issues. It says.

Write a program RandomWalkers.java that takes two integer command-line arguments N and T. In each of T independent experiments, simulate a random walk of N steps and compute the squared distance. Output the mean squared distance (the average of the T squared distances.)

% java RandomWalkers 100 10000
squared distance = 101.446

% java RandomWalkers 100 10000
mean squared distance = 99.1674

% java RandomWalkers 200 1000
mean squared distance = 195.75

I thought I could just do a nested while loop with the outside while counting the number of trials with the inside while being the exact same as above. But It's only printing back the first trial distance, not the average of all of them. I've been messing with it for a couple days and here's how it looks now. Any and all help is appreciated.

package project2;

import java.util.*;
import java.math.*;

public class RandomWalkers {
    public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        Random rand = new Random();
        System.out.println("Enter the number of steps you want to take please.");
        int steps = scan.nextInt();
        System.out.println("Enter the amount of trials you want run please");
        int trials = scan.nextInt();
        double avgDist =0;
        int stepCount =0;
        int trialCount =0;
        int x = 0;
        int y = 0;
        int XorY;
        int dist;

        while(trialCount<trials){

            while(stepCount<steps){
                XorY = rand.nextInt(2);
                dist = rand.nextInt(2);
                if(XorY==0){
                    if(dist==0)
                        dist = -1;
                    x += dist;
                }
                else{
                    if(dist==0)
                        dist = -1;
                    y += dist;
                }
                stepCount ++;


            }
            avgDist += ((x*x) + (y*y));
            trialCount++;
        }
        System.out.println("Average Squared Distancee = " +avgDist/(double)trialCount);
    }
}

You should start making your code more readable and maintainable, even by yourself, by splitting the problems into several units, which will become methods. Here's what you have to do:

  1. Make T experiments. Ech experiment produces a distance
  2. Compute the average of the distances

Note that the first step, which asks the user for the N and T values, could also be a first step. But that isn't even necessary, since the assignment asks to pass them as command line arguments: they're in the array passed to the main() method.

If you write the code for these two steps, you end up with the following code:

double totalDistance = 0;
for (int i = 0; i < t; i++) {
    int distance = makeExperiment(n);
    totalDistance += distance;
}
double averageDistance = totalDistance / t;

So now you just need to implement the makeExperiment() method. But that's easy, since you already implemented it in the first part of the assignment. You just need to remove the useless code (the part which asks N to the user, and which displays the result of the experiment), and to put it into a method which returns the distance.

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