这是我的问题:
一名学生决定提前一点庆祝感恩节的开始。
她的家在大街的 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
}
请帮忙!