java - 不知道为什么这不起作用

标签 java loops average

这是我在学校坚持参加的一个项目。不明白为什么它不会给我平均和最大。该程序按照我想要的方式运行 50 次,但没有为移动次数和总数添加值。

import java.util.*;

public class RandomWalk {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Random rand = new Random();

        int location;
        double average;
        int greatest=0;
        int moves = 0;
        int total = 0;
        int step;

        for (int i = 0; i < 50; i++) {

            location = 4;
            step = rand.nextInt((2 - 1) + 1) + 1;


            while (location < 1 || location > 7) {
                moves ++;
                if (step == 2){
                    location ++;    
                } else {
                    location --;
                }
                if (moves > greatest) {
                    greatest = moves;
                    total += moves;
                }
            }
        }

        average = total / 50;

        System.out.println("The greatest number of steps: " + greatest);
        System.out.println("The average number of steps:  " + average);

     }

}

修复了 for 循环,但它仍然没有给出平均值和最大值。

至于while (location < 1 || location > 7)它应该一直运行到该人站在位置 1 或位置 7 为止。

这是我遇到的问题:

在“随机游走”中,一个人被放置在一座七米长的桥的中心。每一步都会使人随机向前或向后移动 1 米。 创建一个随机游走,确定该人在离开桥之前要走多少步。让应用程序平均 50 次试验,并显示平均步数和最大步数。

感谢您的帮助...

如果我将其更改为:`import java.util.*;

公共(public)类 RandomWalk2 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Random rand = new Random();
    double average;
    int greatest=0;
    int moves;
    int total = 0;
    int step;

    step = rand.nextInt((2 - 1) + 1) + 1;

    int location; //location of man on bridge
    for(int i = 0; i < 50; i++)
    {
       moves = 0;
       moves++;
       location = 4;
       total += moves;
       while(true)
       {
          if (step == 2) {
           location++;
          } else {
           location--;
          }

         if((location < 1) || (location > 7)) break;
       }

      if(moves > greatest) {
      greatest = moves;

      }


      }

    average = total / 50;

    System.out.println("The greatest number of steps: " + greatest);
    System.out.println("The average number of steps:  " + average);


    }

}

` 然后它运行了 50 次,但那家伙只移动了 1 站,所以我的最大和平均值始终显示为 1。

最佳答案

不,它不会循环 50 次,因为你的 for循环条件不正确。 for如果条件为true,则循环继续迭代,不是false 。更改您的状况

for (int i = 0; i == 50; i++) {

for (int i = 0; i < 50; i++) {

然后它将运行直到 i < 50false (50 次)。

关于java - 不知道为什么这不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21788190/

相关文章:

java - 如何在android中使用加速度计跟踪路径?

java - 实现一个 .a 文件(RoboVM 中的静态库)?

java - 如何在 Android Volley 中创建一个新的 newRequestQueue

MongoDB聚合查询以计算用户和支付模型分离时的ARPU

c - 如何将数组的元素数量传递给函数

java - Objectifyfilter 的注释

excel - 循环不会停止,导致溢出

java - 与字符串数组关联的数组中的最小数字

javascript - 如何让多个模态框出现在 while 循环中?

php - 如何从php中的数组中找到平均值?