简体   繁体   English

这里的初学者,我嵌套了while循环问题

[英]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%. 在每个时间步上,酒鬼都会忘记自己所在的位置,并随机地向北,向东,向南或向西走一步,概率为25%。 How far will the drunkard be from the lamp post after N steps? N步后,酒鬼将离灯柱多远?

Write a program RandomWalker.java that takes an integer command-line argument N and simulates the motion of a random walker for N steps. 编写一个程序RandomWalker.java,它接受一个整数命令行参数N并模拟N个步长的随机助步器的运动。 After each step, print the location of the random walker, treating the lamp post as the origin (0, 0). 每个步骤之后,打印随机助行器的位置,将灯柱视为原点(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. 编写一个程序RandomWalkers.java,它使用两个整数命令行参数N和T。在每个T独立的实验中,模拟N步的随机游动并计算平方距离。 Output the mean squared distance (the average of the T squared distances.) 输出平均平方距离(T平方距离的平均值。)

% java RandomWalkers 100 10000 %Java RandomWalkers 100 10000
squared distance = 101.446 平方距离= 101.446

% java RandomWalkers 100 10000 %Java RandomWalkers 100 10000
mean squared distance = 99.1674 均方根距离= 99.1674

% java RandomWalkers 200 1000 %Java RandomWalkers 200 1000
mean squared distance = 195.75 均方根距离= 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. 我以为我可以与外部做一个嵌套的while循环,同时计算内部的试验次数,而和上面的完全一样。 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. 做T实验。 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. 请注意,第一步是向用户询问N和T值。 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. 但这甚至没有必要,因为分配要求将它们作为命令行参数传递:它们在传递给main()方法的数组中。

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. 因此,现在您只需要实现makeExperiment()方法。 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. 您只需要删除无用的代码(向用户询问N并显示实验结果的部分),并将其放入返回距离的方法中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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