0

这是我的问题:

一名学生决定提前一点庆祝感恩节的开始。

她的家在大街的 0 号角,而监狱在大街的 10 号角。学生从拐角 5 开始,向左或向右游荡一个拐角,每个拐角的概率为 0.5;她重复这个过程,直到安全回家或入狱。也就是说,在每个拐角处,醉酒的学生有 50-50 的概率向左或向右摇晃到下一个编号较高或编号较低的拐角处。

编写一个名为drunkWalk() 的方法,使用while 或do-while 循环来模拟醉酒学生的步行;您的方法应返回一个整数,该整数既表示采取了多少步,也表示学生是入狱还是在家。如果您将所采取的步数返回为负数(如果此人入狱,则返回正数),如果此人最终在家,则可以执行此操作。您不应该打印出方法的最终版本中执行的每个步骤,尽管您可能希望在调试时执行此操作。

一旦你的方法工作了,让你的主程序调用你的drinkWalk()方法N次(其中N是一个最终变量)。最后,让它计算并打印学生一次旅行的平均步数。以下是您的程序在运行中可能的样子,其中 N 等于 5:

Here we go again... time for a walk! <br/>
Took 37 steps, and <br/>
Landed at HOME<br/>

Here we go again... time for a walk!<br/>    
Took 19 steps, and <br/>
Landed in JAIL<br/>

Here we go again... time for a walk!<br/>
Took 13 steps, and <br/>
Landed in JAIL<br/>

Here we go again... time for a walk! <br/>
Took 25 steps, and <br/>
Landed in JAIL<br/>

Here we go again... time for a walk!<br/>
Took 15 steps, and <br/>
Landed at HOME<br/>

Average # of steps equals 25.4<br/>

这是我的代码:它编译但我没有得到输出。我认为我的代码过于复杂,但我不知道如何简化它:

class Drunk     
{

// When this code runs, nothing prints out????

  public static void main(String[] args)
  {
    int home = 0; 
    int jail = 10;  

    final int N = 5; 
    int sum = 0;

    int a = drunkWalk(N); 
    sum = sum + a; 

    //System.out.println ("Average # of steps equals" + " " + (a/sum));

  }

  static int drunkWalk(int x)
  {
    int steps; // steps is the number of steps taken by the student
    int total=5;  // total is the starting point of the student (at corner 5)

    while (x > 0); 
    {   
      do 
      { 
        steps = (int) (Math.random() * (10 +  10) - 10); 
        total += steps;
        x = x-1;
      } while (total != 0 || total != 10);
    }

    if (total == 0) 
    {
      System.out.println("Here we go again... time for a walk!");
      System.out.println("Took" + " " + steps + "steps, and");
      System.out.println ("Landed at HOME"); 
    }

    if (total == 10) 
    { 
      System.out.println("Here we go again... time for a walk!");
      System.out.println("Took" + " " + steps + "steps, and");
      System.out.println ("Landed in JAIL"); 
    }

    return steps; // Need to figure out how to add up ALL the steps
  }

请帮忙!

4

2 回答 2

5

;afterwhile终止你的循环。因此,删除;while 语句后的分号:

while (x > 0);// remove semicolon  ;

当您的第一个while循环终止时, valuetotal不会steps改变。

于 2013-11-13T03:18:43.977 回答
0

嘿,您的代码有一个无限循环

do { 
    steps = (int) (Math.random() * (10 +  10) - 10); 
    total += steps;
    x = x-1;
} while (total != 0 || total != 10);

在这里假设您的total = 0thentotal != 10得到满足,因此将继续循环,如果您的total = 10thentotal != 0再次得到满足,则循环继续"YOU HAVE USED ||OPERATOR"。你应该&&这样使用

    do { 
       steps = (int) (Math.random() * (10 +  10) - 10); 
       total += steps;
       x = x-1;
    } while (total != 0 && total != 10);

注意:考虑到您的循环逻辑是您想要的。

于 2015-12-30T06:45:34.207 回答