0 java random parameters return while-loop
这是我的问题:
一名学生决定通过稍微粉碎来提前庆祝感恩节的开始.
她的家位于主街0号角,监狱位于主街10号角.学生从第5角开始,向左或向右徘徊一个角,概率为0.5; 她重复这个过程,直到安全抵达家中或登陆监狱.也就是说,在每个角落,醉酒的学生向左或向右错开50-50的概率,到下一个更高编号或下一个更低编号的角落.
使用while或do-while循环编写名为drunkWalk()的方法,模拟醉酒学生的步行; 你的方法应该返回一个整数,这个整数都表示采取了多少步骤以及学生是在监狱里还是在家里.如果你将这个人作为负数返回,如果这个人进入监狱,你可以这样做,如果这个人最终在家,则可以作为正数.您不应该打印出最终版本的方法中的每个步骤,尽管您可能希望在调试时执行此操作.
一旦你的方法工作,让你的主程序调用你的drunkWalk()方法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/>
Run Code Online (Sandbox Code Playgroud)
这是我的代码:它编译但我没有输出.我认为我的代码过于复杂,但我不知道如何简化它:
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
}
Run Code Online (Sandbox Code Playgroud)
请帮忙!
;在while终止你的循环之后.因此,;在while语句后删除分号:
while (x > 0);// remove semicolon ;
Run Code Online (Sandbox Code Playgroud)
作为你的第一个while循环结束,值total,steps没有得到改变.