繁体   English   中英

Java中的While / Do While循环

[英]While/ Do While loops in Java

这是我的问题:

一名学生决定庆祝感恩节的开始,尽早捣碎,以庆祝这一点。

她的家在大街上的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/>

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

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
  }

请帮忙!

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

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

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

嘿,您的代码有一个INFINITE循环

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

在这里,假设您的total = 0然后total != 10得到满足,因此循环将继续进行;如果您的total = 10然后total != 0再次得到满足,则循环继续“您已使用||运算符” 您应该这样使用&&

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

注意:根据需要考虑循环逻辑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM