gpt4 book ai didi

java - Java 中的 While/Do While 循环

转载 作者:行者123 更新时间:2023-12-01 17:19:14 25 4
gpt4 key购买 nike

这是我的问题:

一名学生决定庆祝感恩节的开始被一点点粉碎而提前打破一点。

她的家位于主街 0 号角, jail 位于主街 10 号角街道。学生从第 5 号角开始,向左或向右移动一个角右边的概率为 0.5;她重复这个过程直到到达安全回家或入狱。也就是说,在每个角落,醉酒的学生都有50-50 的概率向左或向右错开,到下一个更高编号或下一个编号较低的角。

使用 while 或 do-while 循环编写一个名为醉Walk() 的方法,该方法模拟醉酒学生的行走;你的方法应该返回一个整数,既指示已采取了多少步,又指示是否学生被关进 jail 或家里。如果您返回数量,则可以执行此操作如果该人入狱,则采取的步骤为负数,如果该人入狱,则采取的步骤为正数如果此人最终在家,则提供号码。您不应该打印出所采取的每个步骤在该方法的最终版本中,尽管您可能希望在您正在调试。

一旦你的方法工作了,就可以调用你的主程序了你的醉Walk()方法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
}

请帮忙!

最佳答案

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

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

当您的第一个 while 循环终止时,值 totalsteps 不会更改。

关于java - Java 中的 While/Do While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19944572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com